css 垂直居中

有这么几个说明

MDN:

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.

Most of the time, absolutely positioned elements have auto values of height and width computed to fit the contents of the element. However, non-replaced absolutely positioned elements can be made to fill the available space by specifying (as other than auto) both top and bottom and leaving heightunspecified (that is, auto). Likewise for left, right, and width.

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

 

.Center-Container {
  position: relative;
}

.Absolute-Center {
  height: 50%;
  overflow: auto;
  position: absolute;
  margin: auto; /*关键*/
  top: 0; left: 0; bottom: 0; right: 0;
}

Ref:http://blog.csdn.net/freshlover/article/details/11579669

其本质应该是,通过将top和bottom设置为0而形成top与bottom的冲突,迫使margin垂直方向均分以满足top和bottom都为0的要求。

发表评论

电子邮件地址不会被公开。