水平垂直居中的几种解决方案
<div class="sup">
<div class="sub"></div>
</div>
- 利用CSS3的弹性盒子:(父元素display:flex;子元素margin:auto;)
.sup{
width:400px;
height:400px;
background-color:#ccc;
display:flex;
}
.sub{
width:100px;
height:100px;
background-color:#000;
margin:auto;
}
- flex布局:(父元素display:flex;justify-content:center;align-items:center;)
.sup{
width:400px;
height:400px;
background-color:#ccc;
display:flex;
justify-content:center;
align-items:center;
}
.sub{
width:100px;
height:100px;
background-color:#000;
}
- position 搭配 margin
父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后减去元素自身宽度的一半就可以实现
.sup{
width:400px;
height:400px;
background-color:#ccc;
position:relative;
}
.sub{
width:100px;
height:100px;
background-color:#000;
position:absolute;
top:50%;
left:50%;
margin:-50px 0px 0px -50px;
}
.sup{
width:400px;
height:400px;
background-color:#ccc;
position:relative;
}
.sub{
width:100px;
height:100px;
background-color:#000;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}