一、文本居中
.center-text {
text-align: center;
}
二、块级元素居中
对于块级元素(如图片、div等),可以使用Flexbox布局。
示例1:水平和垂直居中
.center-block {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100%; /* 确保容器有高度 */
}
示例2:仅水平居中
.center-horizontal {
display: flex;
justify-content: center;
}
三、整个页面居中
使用Flexbox布局。
.page-center {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh; /* 视口高度 */
}
四、使用绝对定位
对于绝对定位元素,可以通过设置top
、left
、transform
属性来居中。
.center-absolute {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}