CSS - margin top of 50% is more than 50%

懵懂的女人 提交于 2019-12-04 07:11:51
Terry

This is because when it comes to top/bottom margins and paddings in percentages, the values will be taken as the fractional width of the parent element, not the height. According to the W3C definition:

The [margin] percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

This question has been addressed before in StackOverflow - see here.


Suggestion: If you would want to position an element in the center vertically, you can use the following trick instead:

  1. Position the child element absolutely
  2. Declare dimensions for the parent, such that the parent's dimensions do not rely on those of the child
  3. Position the child element 50% from the top
  4. Use a nifty trick of CSS 2D translation.

Here's the modified CSS from your fiddle that works:

.content header {
    width: 100px;
    height: 100px;
    top: 50%;
    background: red;
    position: absolute;
    -webkit-transform: translate(0, -50%);
    transform: translate(0, -50%);
}

http://jsfiddle.net/teddyrised/73xkT/7/

VenomVendor

Change child's position from relative to absolute.
Instead of margin-top use top

http://jsfiddle.net/73xkT/5/

.content header {
  top: 50%;
  position: absolute;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!