今天介绍几种让一个盒子在另一个盒子中居中的方法;
内联元素:给子盒子设置display属性为inline,然后在设置line-height为父盒子的高度
html:
<div class="box">
<p>p标签</p>
</div>
css:
.box {
width: 200px;
height: 200px;
margin: 100px auto;
border: 1px solid #f00;
text-align: center;
}
p {
display: inline;
line-height: 200px;
background-color: #f40;
}
结果:
对于内联元素垂直居中的方法还有很多,此处只介绍一种,重点介绍两种块状元素垂直居中的方法。
块状元素:
1、父盒子设置display属性为flex,flex-direction:column, justify-content: center;
html:
<div class="box">
<div class="small"></div>
</div>
css:
.box {
width: 200px;
height: 200px;
margin: 100px auto;
border: 1px solid #f00;
display: flex;
flex-direction: column;
justify-content: center;
}
.small {
width: 100px;
height: 100px;
background-color: #f40;
}
结果:
2、设置父盒子display属性值为 -webkit-box,;-webkit-box-orient:horizontal;-webkit-box-align:center;
html:
<div class="box">
<div class="small"></div>
</div>
css:
.box {
width: 200px;
height: 200px;
margin: 100px auto;
border: 1px solid #f00;
display:-webkit-box;
-webkit-box-orient:horizontal;
-webkit-box-align:center;
}
.small {
width: 100px;
height: 100px;
background-color: #f40;
}
结果:
让元素垂直居中的方法还有很多,这里就不一一介绍了。本人水平有限,写的不好的地方欢迎指出,共同讨论。