水平居中如果不太熟悉盒子模型的话属实不太好理解,其实就是控制其他属性来让border之内的内容被控制在父容器中间就行了,最经典的就是使用{margin: 0 auto}了,控制其上下外边框为0,左右两边自动根据父容器的宽度调整为相同的数值把内容卡在中间就可以了。
<style> .parent{ display: block; width: 200px; border: 1px solid; } .child{ display: block; margin: 0 auto; width: 100px; height: 50px; background-color: aqua; } </style> <body> <div class="parent"> <div class="child"></div> </div> </body>
垂直对齐内容则有挺多办法的,有通过使用设置position:absolute把容器移动到父容器的50%距离上然后上移一半height的,这个通过margin-top设置为负数之类的都可以解决,或者设置display: inline-block;和vertical-align: middle;也可以做到,还有设置position为表样式的,方法很多。
<style> *{padding: 0;margin:0;} .box{ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; width: 100px; height: 100px; border: 1px solid red; } </style> <body> <div class="box"> </div> </body>