CSS居中是页面布局中最常用的需求之一,下面介绍两个盒子如何居中的几种方法。
/* 方法一:使用margin */
.box {
width: 200px;
height: 100px;
background-color: #f00;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* 方法二:使用flex布局 */
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.box {
width: 200px;
height: 100px;
background-color: #f00;
} 方法一是将盒子的position属性设置为absolute,然后利用margin属性将盒子水平垂直居中。值得注意的是,需要将top、left、bottom、right设置为0,否则会造成父级元素溢出的问题。
方法二使用的是flex布局,将父级元素的display属性设置为flex,然后使用justify-content和align-items属性分别进行水平和垂直居中。发现这种方法比前一种方法更简单且适用性更广。