盒子居中的方法
如下要实现的效果图:
水平垂直居中
1、定位的方式
父盒子设置相对定位,子盒子设置绝对定位
<div class="bigbox">
<div class="smallbox"></div>
</div>
.bigbox{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.smallbox{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
2、flex布局的方式
给父盒子开启flex弹性布局,设置justify-content与align-items成center即可
.bigbox{
width: 200px;
height: 200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.smallbox{
width: 100px;
height: 100px;
background-color: blue;
}
3、table-cell布局
父盒子设置table-ceil,vertical-align 是让子盒子垂直居中,在子盒子设置margin:0 auto;为了实现让子盒子水平居中。
.bigbox{
width: 200px;
height: 200px;
background-color: red;
display: table-cell;
vertical-align: middle;
}
.smallbox{
width: 100px;
height: 100px;
background-color: blue;
margin: 0 auto;
}
4、grid布局
在父盒子开启grid布局,子盒开启justify-self,align-self
.bigbox{
width: 200px;
height: 200px;
background-color: red;
display: grid;
}
.smallbox{
width: 100px;
height: 100px;
background-color: blue;
justify-self: center;
align-self: center;
}
这篇文章关于盒子居中的四种简单实用的方法我就分享到这里啦!