一、水平居中
-
margin: auto;
设置子容器margin
属性,可使元素在父容器内水平居中
<div class="bg">
<div class="content"></div>
</div>
...
.bg {
background-color: gray;
width: 500px;
height: 100px;
}
.content {
background-color: red;
width: 100px;
height: 50px;
margin: auto;
}

二、垂直居中
-
line-height:
设置父容器的line-height
与height
属性,可使容器内部的元素垂直居中;
<div class="bg">
<div class="content">aaaa</div>
</div>
...
.bg {
background-color: gray;
width: 500px;
height: 100px;
line-height: 100px; // 这里 line-height与height高度一致
}
.content {
background-color: red;
width: 100px; // content不能设置高度
}
line-height是设置在父容器内,使容器内部子元素垂直居中;
-
padding:
设置父容器的padding与子元素的高度,会自动计算出父容器的高度,并在子元素会垂直居中在父容器内;
<div class="bg">
<div class="content"></div>
</div>
...
.bg {
background-color: gray;
width: 500px;
padding: 25px; // 设置padding,但是不要设置高度
}
.content {
background-color: red;
width: 100px;
height: 50px; // 设置高度
}

-
transform:
设置子元素的transform
可实现垂直居中
<div class="bg">
<div class="content"></div>
</div>
...
.bg {
background-color: gray;
width: 500px;
height: 100px;
}
.content {
background-color: red;
width: 100px;
height: 50px;
transform: translate(0, 50%); // 垂直居中
}
网友评论