<style>
<body>
<div class="box">
<div class="child"></div>
</div>
</body>
如上述代碼,box高度固定曼氛,而child盒子中的內(nèi)如不固定豁辉,高度隨內(nèi)如變化,要是child在box中垂直水平都居中舀患,在此為大家介紹如下三種方法:
1.通過display:table-cell;屬性徽级;
<style>
.box{
width:200px;
height:200px;
border:1px solid red;
display:table-cell;
text-align:center;
vertical-align:middle;
}
.child{
width: 100px;
height: 100px;
background-color: green;
display:inline-block;
}
</style>
2.通過定位position,注意聊浅,關(guān)鍵的child的margin:auto;一定不能忘記設(shè)置餐抢;
<style>
.box{
width:200px;
height:200px;
border:1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background-color:green;
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
</style>
3.通過position定位和 transform:translate(-50%,-50%)现使;
.box{
width:300px;
height:200px;
border:1px solid red;
position: relative;
}
.child{
width: 150px;
height: 100px;
background-color: green;
position: absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
當(dāng)然通過flex盒子模型也是可是的,在此就不再給出代碼演示弹澎,具體可以了解一下flex盒子模型