我们经常用margin:0 auto来实现水平居中,而一直认为margin:auto不能实现垂直居中……实际上,实现垂直居中仅需要声明元素高度和下面的css:
.absolute-center { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
优点:
1.支持跨浏览器,包括ie8-ie10.
2.无需其他特殊标记,css代码量少
3.支持百分比%属性值和min-/max-属性
4.只用这一个类可实现任何内容块居中
5.不论是否设置padding都可居中(在不使用box-sizing属性的前提下)
6.内容块可以被重绘。
7.完美支持图片居中。
缺点:
1.必须声明高度(查看可变高度variable height)。
2.建议设置overflow:auto来防止内容越界溢出。(查看溢出overflow)。
3.在windows phone设备上不起作用。
浏览器兼容性:
chrome,firefox, safari, mobile safari, ie8-10.
绝对定位方法在最新版的chrome,firefox, safari, mobile safari, ie8-10.上均测试通过。
对比表格:
绝对居中法并不是唯一的实现方法,实现垂直居中还有些其他的方法,并各有各的优势。采用哪种技术取决于你的浏览器是否支持和你使用的语言标记。这个对照表有助于你根据自己的需求做出正确的选择。
technique
browser support
responsive
overflow
resize:both
variable height
major caveats
absolute centering
modern & ie8+
yes
scroll, can overflow container
yes
yes*
variable height not perfect cross-browser
negative margins
all
no
scroll
resizes but doesn't stay centered
no
not responsive, margins must be calculated manually
transforms
modern & ie9+
yes
scroll, can overflow container
yes
yes
blurry rendering
table-cell
modern & ie8+
yes
expands container
no
yes
extra markup
inline-block
modern, ie8+ & ie7*
yes
expands container
no
yes
requires container, hacky styles
flexbox
modern & ie10+
yes
scroll, can overflow container
yes
yes
requires container, vendor prefixes
解释:
通过以上描述,绝对居中(absolutecentering)的工作机理可以阐述如下:
1、在普通内容流(normal content flow)中,margin:auto的效果等同于margin-top:0;margin-bottom:0。
w3c中写道if 'margin-top', or'margin-bottom' are 'auto', their used value is 0.
2、position:absolute使绝对定位块跳出了内容流,内容流中的其余部分渲染时绝对定位部分不进行渲染。
developer.mozilla.org:...an element that is positioned absolutely is taken out of the flow and thustakes up no space
3、为块区域设置top: 0; left: 0; bottom: 0; right: 0;将给浏览器重新分配一个边界框,此时该块block将填充其父元素的所有可用空间,父元素一般为body或者声明为position:relative;的容器。
developer.mozilla.org:for absolutely positioned elements, the top, right, bottom, and left propertiesspecify offsets from the edge of the element's containing block (what theelement is positioned relative to).
4、 给内容块设置一个高度height或宽度width,能够防止内容块占据所有的可用空间,促使浏览器根据新的边界框重新计算margin:auto
developer.mozilla.org: the margin of the[absolutely positioned] element is then positioned inside these offsets.
5、由于内容块被绝对定位,脱离了正常的内容流,浏览器会给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', solvethe equation under the extra constraint that the two margins get equal values.aka: center the block vertically
这么看来, margin:auto似乎生来就是为绝对居中(absolute centering)设计的,所以绝对居中(absolute centering)应该都兼容符合标准的现代浏览器。
简而言之(tl;dr):绝对定位元素不在普通内容流中渲染,因此margin:auto可以使内容在通过top: 0; left: 0; bottom: 0;right: 0;设置的边界内垂直居中。
以上就是css绝对定位居中技术优缺点图表详解的详细内容。
