CSS中设置盒子居中可以分为水平居中和垂直居中两种方式,下面将分别进行介绍。水平居中:.box{ width: 200px; height: 100px; margin: 0 auto; backgr
CSS中设置盒子居中可以分为水平居中和垂直居中两种方式,下面将分别进行介绍。
水平居中:
.box{ width: 200px; height: 100px; margin: 0 auto; background-color: gray; }
上述代码中,将宽度设置为200px,将左右外边距都设置为auto,这样就可以实现水平居中的效果。其中margin的简写方式可以写成margin:0 auto;。
垂直居中:
.parent{ display: flex; justify-content: center; align-items: center; background-color: pink; } .box{ width: 200px; height: 100px; background-color: gray; }
上述代码中,首先需要将容器的display属性设置为flex,然后通过justify-content和align-items两个属性分别设置盒子在水平和垂直方向上的对齐方式,再将盒子本身的宽高设置为固定值,这样就可以实现垂直居中的效果。其中justify-content属性可以取值center,表示水平居中,align-items属性也可以取值center,表示垂直居中。
粉丝
0
关注
0
收藏
0