在前端开发过程中,经常需要将盒子居中显示。这里推荐几种CSS方法来实现盒子居中。水平居中(行内/行内块元素):.parent{ textalign: center; } .child{ display...
在前端开发过程中,经常需要将盒子居中显示。这里推荐几种CSS方法来实现盒子居中。
水平居中(行内/行内块元素):
.parent{
text-align: center;
}
.child{
display: inline-block; /*或者display: inline;*/
} 水平居中(块级元素):
.parent{
display: flex;
justify-content: center;
}
.child{
display: block;
} 水平垂直居中(绝对定位):
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} 水平垂直居中(flex布局):
.parent{
display: flex;
justify-content: center;
align-items: center;
}
.child{
display: block;
} 以上是几种常见的CSS实现盒子居中的方法,根据实际需求和情况选择合适的方式即可。