使子容器在父容器中垂直居中的六种方法.
第一种,使用定位来实现
.wrap1
{
width: 200px;
height: 200px;
background-color: #00FFFF;
position: relative;
}
.index1
{
width: 50px;
height: 50px;
background-color: #008000;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
<!-- 使用定位 -->
<div class="wrap1">
<div class="index1">
</div>
</div>
第二种,使用定位结合margin来实现
.wrap2
{
width: 200px;
height: 200px;
background-color: #0FFF00;
position: relative;
}
.index2
{
width: 50px;
height: 50px;
background-color: #008000;
position: absolute;
left: 50%; /*相对父容器宽度距离一半*/
top: 50%; /*相对父容器高度一半*/
margin-left: -25px; /*当前容器的宽度一半*/
margin-top: -25px; /*当前容器的高度一半*/
}
<!-- 使用定位结合margin -->
<div class="wrap2">
<div class="index2">
</div>
</div>
第三种,使用transform结合margin实现
.wrap3
{
width: 200px;
height: 200px;
background-color: #FF0000;
}
.index3
{
width: 50px;
height: 50px;
background-color: #2F2182;
transform: translate(100px,100px);/*相对父元素的一半高度和宽度*/
margin-left: -25px;
margin-top: -25px;
}
第四种,使用flex布局,针对所有子元素
.wrap4
{
width: 200px;
height: 200px;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
.index4
{
width: 50px;
height: 50px;
background-color: #FFF;
}
<!-- 使用flex布局,针对所有元素 -->
<div class="wrap4">
<div class="index4">
</div>
</div>
使用flex布局,针对单个子元素
.wrap5
{
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
}
.index5
{
width: 50px;
height: 50px;
background-color: #FFF;
align-self: center;
}
第六种,使用grid布局(类似于flex布局)
/* grid居中写法 */
.wrap6
{
width: 200px;
height: 200px;
background-color: salmon;
display: grid;
justify-content: center;
align-content: center;
}
.index6
{
width: 50px;
height:50px;
background-color: #0FFF00;
}
<!-- grid居中 -->
<div class="wrap6">
<div class="index6">
</div>
</div>