好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

CSS6种完全居中最佳实践(整理)_html/css_WEB-ITnose

2016年4月28日

1.最佳法:

.Absolute-Center {          width: 50%;          height: 50%;          overflow: auto;          margin: auto;          position: absolute;          top: 0; left: 0; bottom: 0; right: 0;          background-color: red;        } 

在线演示

在普通文档流里,margin: auto; 的意思是设置元素的margin-top和margin-bottom为0。

W3.org:?If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0.

设置了position: absolute; 的元素会变成块元素,并脱离普通文档流。而文档的其余部分照常渲染,元素像是不在原来的位置一样。

Developer.mozilla.org:?…an element that is positioned absolutely is taken out of the flow and thus takes up no space

设置了top: 0; left: 0; bottom: 0; right: 0; 样式的块元素会让浏览器为它包裹一层新的盒子,因此这个元素会填满它相对父元素的内部空间,这个相对父元素可以是是body标签,或者是一个设置了position: relative; 样式的容器。

Developer.mozilla.org:?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).

给元素设置了宽高以后,浏览器会阻止元素填满所有的空间,根据margin: auto; 的要求,重新计算,并包裹一层新的盒子。
Developer.mozilla.org:?The margin of the [absolutely positioned] element is then positioned inside these offsets.

既然块元素是绝对定位的,又脱离了普通文档流,因此浏览器在包裹盒子之前会给margin-top和margin-bottom设置一个相等的值。
W3.org:?If none of the three [top, bottom, height] are ‘auto’: If both ‘margin-top’ and ‘margin-bottom’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values.?AKA: center the block vertically

使用“完全居中”,有意遵照了标准margin: auto; 样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。

优点:

跨浏览器,兼容性好(无需hack,可兼顾IE8~IE10) 无特殊标记,样式更精简 自适应布局,可以使用百分比和最大最小高宽等样式 居中时不考虑元素的padding值(也不需要使用box-sizing样式) 布局块可以自由调节大小 img的图像也可以使用

同时注意:

必须声明元素高度 推荐设置overflow:auto;样式避免元素溢出,显示不正常的问题 这种方法在Windows Phone上不起作用



2.负margin法:

.negative-margin {        width: 300px;        height: 200px;        padding: 20px;        position: absolute;        top: 50%; left: 50%;        margin-left: -170px; /* (width + padding)/2 */        margin-top: -120px; /* (height + padding)/2 */} 

在线演示



3.transform法:

.transform {   width: 50%;  margin: auto;  position: absolute;  top: 50%; left: 50%;  -webkit-transform: translate(-50%,-50%);      -ms-transform: translate(-50%,-50%);          transform: translate(-50%,-50%);} 

在线演示



4.inner-block法:

HTML:

查看更多关于CSS6种完全居中最佳实践(整理)_html/css_WEB-ITnose的详细内容...

  阅读:35次