Definition of the "margin-top" in percentage of a "div" works in a strange way

2

I have a page .xhtml and the first element to be placed is a div ( content ) and I set it to a top margin ( margin-top ) of 30% p>

Supposedly, this percentage should be taken from the height of my screen, in my case I have a screen of 1600 × 795 and the 30% would be taken from the 795px.

See what happens:

#content
{
  width: 300px;
  height: 200px;
  margin: 0 auto;
  margin-top: 50%;
  background: red;
}
<div id="content">
</div>

In the example I put 50% of margin-top to pass the perception of what happens. It should be 50% of the top plus it seems to have gone down a lot more.

    
asked by anonymous 20.10.2014 / 13:26

4 answers

2

Actually if you are simply by logic would imply that margin-top and margin-bottom when specified in % would be a value relative to the height of the parent element, but that is not how it works.

When the margin is specified in '%' it will always be relative to the width ( width ) of the parent element, you can check it easily by resizing the window, you will see that the element will change position only when you change the width of the window.

    
20.10.2014 / 13:57
0

I moved a little in your CSS and there:

#content
{
width: 300px;
height: 200px;
position: absolute;
top: 0; 
bottom: 0;
left: 0; 
right: 0;
margin: auto;
background: red;
}
<div id="content">
</div>

I believe that this will solve your problem

    
20.10.2014 / 13:39
0

add in css of div #content

display: table-caption;
    
20.10.2014 / 15:21
0

As already mentioned, margin and padding with percentage use the width of the element. The margin is based on the parent element. And the padding is based on the element itself.

If your intention was that the element, ie your #content be centralized, you should do as in the example below.

 #content {
     position: absolute;
     display: block;
     width: 200px;
     height: 200px;
     top: calc(50% - 100px);
     left: calc(50% - 100px);
 }

In the example I say that my #content will have a distance of 50% from the top of the next parent element that has position: relative , less than half the height of my element, because when we use the top attribute, it is referenced by the top of the element and not by the center. In the same way for left , only the distance is 50% less than half the width of the element.

    
28.11.2016 / 14:22