居中布局

水平居中和垂直居中

水平居中方法1(margin:0 auto):

<div style="width: 300px ; height:300px; background-color: red ;">
    <div style="width: 100px;height:100px;background-color: yellow ; margin: 0 auto"></div>
</div>

垂直居中方法1(table-cell + vertical-align:middle):

<div style="width: 300px ; height:300px; background-color: red ;display:table-cell;vertical-align: middle">
    <div style="width: 100px;height:100px;background-color: yellow ;"> </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; 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>

水平居中效果图:

垂直居中效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值