css篇之absolute绝对定位元素居中技巧

本文介绍了一种新颖的CSS绝对定位元素居中方法:通过设置top、right、bottom、left为0,并配合margin:auto实现。这种方法适用于需要精确居中的场景,但需注意当子元素尺寸较大时可能存在的限制。

一般地,居中绝对定位元素,left:50%;top:50%;margin负值或者通过transform也可达到效果。
今天发现另一个技巧,利用,top,left,right,bottom取值0,再magin:auto,即可实现居中。
原因:

For absolutely positioned elements, the top, right, bottom,and left properties specify offsets from the edge of the element's containing block (what the element is positioned relative to).The margin of the element is then positioned inside these offsets.
<div class='box>
    <div class='jz'></div>
</div>
div.box{
   position: relative;
   height: 300px;
   background: #989eaa;
}
div.fz{
   width: 100px;
   height: 100px;
   background: #499682;
   position: absolute;
   top:0;
   left: 0;
   right: 0;
   bottom: 0;
   margin:auto;
}

注:子元素大的话,上下可居中,左右失效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值