一个不定宽高的div如何实现水平垂直居中
三种方法实现图中所示的居中
flex布局
<!-- flex布局 -->
<section>
<style>
.parentBox{
width: 200px;
height: 200px;
display: flex;
justify-content: space-around;
align-items: center;
background: pink;
}
.parentBox>div{
background: plum
}
</style>
<div class="parentBox">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
</section>
定位+css3
<!-- 定位 -->
<section>
<style>
.parentBox1{
width: 200px;
height: 200px;
position: relative;
background: brown;
}
.parentBox1>div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: antiquewhite;
}
</style>
<div class="parentBox1">
<div class="three">three</div>
</div>
</section>
table-cell
<!-- table-cell -->
<section>
<style>
.parentBox2{
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
height: 200px;
background: khaki;
}
.parentBox2>div{
vertical-align: middle;
display: inline-block;
}
</style>
<div class="parentBox2">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
</section>
注意:子div中必须有内容,才能呈现出图中的效果,因为子div没有宽高,全靠内容撑起来