Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

I want a child div with a op-margin via percentage. The y-position shall be 50% percent of the parent div. But it is somehow more. Why isn't it 50% ?

js fiddle

HTML

<div class="content">
  <header></header>
</div>

CSS

.content {
  width: 300px;
  height: 200px;
  background: blue;
  position: relative;
  clear: both;
 }

.content header {
   width: 100px;
   height: 100px;
   margin-top: 50%;
   background: red;
   position: relative;
   float: left;
}
like image 672
user2952265 Avatar asked Dec 14 '13 16:12

user2952265


People also ask

How do I reduce top margin in CSS?

Adjusting the Margin Size of an HTML Element With CSS You can remove this margin by setting the top and left margin to zero. Like the padding and border, the sizes of specific sides of the margin can be set using margin-left , margin-right , margin-top , and margin-bottom .

Can you use percentages in margin CSS?

You can combine fixed value and percentage values in the CSS margin property. Negative values are allowed in the CSS margin property. When the value is provided as a percentage, it is relative to the width of the containing block. See also margin-top, margin-bottom, margin-left, and margin-right.

How does margin-top work in CSS?

The margin-top CSS property sets the margin area on the top of an element. A positive value places it farther from its neighbors, while a negative value places it closer.


1 Answers

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/

like image 91
Terry Avatar answered Sep 23 '22 06:09

Terry