CSS中如何实现盒子居中?盒子居中主要有三种方式,分别是水平居中、垂直居中和水平垂直居中。下面将分别介绍这三种方法的实现。 一、水平居中的实现方法 1. 设置margin属性为auto box { w...
CSS中如何实现盒子居中?
盒子居中主要有三种方式,分别是水平居中、垂直居中和水平垂直居中。下面将分别介绍这三种方法的实现。
一、水平居中的实现方法
1. 设置margin属性为auto
box {
width: 200px;
margin: 0 auto;
}
2. 使用flex布局
.container {
display: flex;
justify-content: center;
}
二、垂直居中的实现方法
1. 使用绝对定位+负边距
.container {
position: relative;
}
.box {
position: absolute;
top: 50%;
margin-top: -50px; /* 元素高度的一半 */
}
2. 使用行高实现
.box {
display: inline-block;
height: 100px;
line-height: 100px; /* 与盒子高度一致 */
}
三、水平垂直居中的实现方法
1. 使用flex布局
.container {
display: flex;
justify-content: center;
align-items: center;
}
2. 使用绝对定位+负边距
.container {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}