CSS是一种用于定义网页样式的语言。它提供了很多给网页添加样式的属性,其中之一就是居中盒子。下面我们一起来了解CSS如何实现这个功能。
.box{width: 200px;margin: 0 auto;}.box{height: 200px;position: absolute; top: 50%;margin-top: -100px; }.box{width: 200px;height: 200px;position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -100px; }.container{display: flex;justify-content: center;align-items: center;}
以上就是CSS居中盒子的几种常见方法。其中,水平居中是最简单的,只需要给盒子设置一个固定宽度,然后设置左右margin的值为auto即可。垂直居中和水平垂直居中需要用到绝对定位和负margin。弹性盒子水平垂直居中是CSS3新增的强大功能,可以更方便地实现居中效果。