5: Percentages and Margins


#1

Hi there,

For altering the margin using percentages, I'm still a bit confused as to what the percentages represent. Can someone please explain please.

Also if I make the margin-top and margin-bottom both 7.5% for example, I would expect there to be no change? But this isn't the case. Can someone please explain this.

Thanks,

Kind regards,

Tim


#2

Percentage always reverts to the parent. If the parent is 600px wide, a child element with 10% margins will be 480px wide. If it has a 3px border, the viewport will be 474px wide.

<div style="width: 602px; border: 1px solid blue">
  <div style="width: auto; margin: 10%; border: 3px double green">
      <br><br><br>
  </div>
</div>

I don't have a sandbox to test this, but if you find one, let us know what you get.


#3

If a there two divs: div 2 is nested inside div 1, and div 1 has a width of 600px. And I made margin-top and margin-bottom 10%, does the height of div 2 decrease by 120px? Or would margin-top cause the div to shift downwards by 60px and then margin-bottom cause the div to shift back upwards by 60px (effectively making no change)?

Thanks


#4

Top and bottom margins are in force, but less obvious. The content forces the height. It's not something we can easily specify. This has always been a problem. Containment, and thus added structure has usually been the solution. Structure to a purist is something of grave concern.


#5

Sorry I don't exactly understand what you mean by 'in force'. So margin-top actually decreases the height of the element opposed to just pushing it down (while maintaining its dimensions)?


#6

Not at all. It just puts the element that much further down. Likewise, margin bottom just pushes the page length that much further.


#7

Sorry about my questions.

So margin-bottom won't push the element upwards but instead just lengthen the page (to make the specified margin)?


#8

On a page element that we wish to keep within a restrictive height, we need to specify in pixels (actually % will work, too, but it's a nightmare), and then declare how the browser should handle overflow. The natural response of the browser is to make the viewport height fit the content. If we restrict this height then we need to introduce the overflow-y property.

height: 400px;
overflow-y: scroll;

or some such, It's been a while since I really engaged in this.


#9

Exactly. There is no push upwards in CSS. That is unless we bring in negative margins; another discussion that we should not get bogged down in at present.


#10

Thanks for the explanation. I get it now.:]