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

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

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;
}

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

相关文章
相关标签/搜索