css盒子垂直居中的5种方式

前端开发   发布日期:2025年08月26日   浏览次数:351

第一种,常用于垂直居中盒子的文字,需要知道盒子高度,行高不能设置百分比

text-align:center;
line-height:盒子本身高度

第二种,使用display:table和display:table-cell配合,两个必须分别作用于父盒子和子盒子

display:table-cell;
vertical-align:middle;

第三种,使用flex布局,不需要知道宽高,写在父盒子

display:flex;
justify-content:center;
align-item:center;

第四种,使用position定位

position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;

第五种,也是使用position定位

position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);

以上就是css盒子垂直居中的5种方式的详细内容,更多关于css盒子垂直居中的5种方式的资料请关注九品源码其它相关文章!