CSS(Cascading Style Sheets)是一种样式表语言,用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档的外观和格式。居中是指将元素放置在页面的中心位置。
/* 使用margin自动填充 */
.center-horizontal {
margin: 0 auto;
width: 50%;
}
/* 使用Flexbox */
.container {
display: flex;
justify-content: center;
}
/* 使用Grid */
.container {
display: grid;
place-items: center;
}
/* 使用Text-align */
.container {
text-align: center;
}/* 使用Flexbox */
.container {
display: flex;
align-items: center;
height: 100vh; /* 使容器高度占满整个视口 */
}
/* 使用Grid */
.container {
display: grid;
place-items: center;
height: 100vh;
}
/* 使用绝对定位 */
.center-vertical {
position: absolute;
top: 50%;
transform: translateY(-50%);
}/* 使用Flexbox */
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* 使用Grid */
.container {
display: grid;
place-items: center;
height: 100vh;
}
/* 使用绝对定位 */
.center-both {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}margin: 0 auto;时元素没有居中?原因:通常是因为元素的宽度没有设置或者设置为100%。 解决方法:确保元素有一个固定的宽度。
.center-horizontal {
margin: 0 auto;
width: 50%;
}原因:可能是容器的高度没有设置或者设置为0。 解决方法:确保容器有一个明确的高度。
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}原因:可能是父元素没有相对定位。 解决方法:确保父元素有一个相对定位。
.parent {
position: relative;
}
.center-both {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}