元素居中布局
作者:互联网
水平居中和垂直居中
水平居中方法1(margin:0 auto):
垂直居中方法1(table-cell + vertical-align:middle):
(以下因为在编辑器上截图显示不全,故只上代码)
水平居中方法2(绝对定位):
<div style="width: 300px ; height:300px; background-color: red; position: relative">
<div style="width: 100px;height:100px;background-color: yellow ;position: absolute; left:50%;margin-left: -50px"></div>
</div>
同理对应垂直居中方法2:
<div style="width: 300px ; height:300px; background-color: red; position: relative">
<div style="width: 100px;height:100px;background-color: yellow ;position: absolute; top:50%;margin-top: -50px"></div>
</div>
水平居中方法3(子div浮动+相对定位):
<div style="width: 300px ; height:300px; background-color: red ;">
<div style="float:left;margin-left:50%; position:relative; left:-50px;width: 100px;height:100px;background-color: yellow ; "></div>
</div>
同理对应垂直居中方法3:
<div style="width: 300px ; height:300px; background-color: red ;">
<div style="float:left;margin-top:50%; position:relative; top:-50px;width: 100px;height:100px;background-color: yellow ; "></div>
</div>
水平居中方法4(flex):
<div style="display:flex; justify-content:center ;width: 300px ; height:300px; background-color: red ;">
<div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>
同理垂直居中方法4:
<div style="display:flex; align-items:center;width: 300px ; height:300px; background-color: red ;">
<div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>
标签:居中,同理,布局,定位,元素,水平,垂直,方法 来源: https://www.cnblogs.com/btsn/p/11610436.html