本文主要介绍如何使元素居中显示的几种方法,当然方法有很多,现在记录的不过是笔者目前能够想到的几种:定位、table-cell、增加空span、弹性盒模型。
html样式如下:
<div class="box">
<div class="box1"></div>
</div> css样式如下:
.box{
width:600px;
height:600px;}类名为.box1的div宽高未定。
方法一(定位)
.box{
width:600px;
height:600px;
position:relative;
}
.box1{
position:absolute;
left:50%;
top:50%;
transfrom:translate(-50%,-50%);
} 方法二(table-cell).box{
width:600px;
height:600px;
display:table-cell;
text-align:center;
vertical-align:middle;
}
.box1{
display:inline-block;
vertical-align:top;
}
方法三(给box中增加一个空span)
<div class="box">
<span></span>
<div class="box1"></div>
</div>.box{
width:600px;
height:600px;
}
.box span{
display:inline-block;
vertical-align:middle;
height:100%;
}
.box1{
display:inline-block;
vertical-align:middle;
}方法四(弹性盒模型)
.box{
width:600px;
height:600px;
display:flex;
justify-content:center;
align-items:center;
}
本文介绍了使用CSS实现元素居中的四种方法:定位、table-cell、增加空span及弹性盒模型。每种方法均通过示例代码进行说明,适用于不同场景的需求。
1863

被折叠的 条评论
为什么被折叠?



