2

I have been trying to convert my site to be more responsive by setting margins, etc. as percentages. I converted my margin-left: 29px; into margin-left: 1.510416%; based on the width of the page. Yet when I tried to do the same based on the height of the page, which upon inspection was 955px,(setting margin-top:25px as margin-top: 2.617801047), the element moved down significantly.

Is the site seeing the height of the page as significantly longer than that shown? When I set margin-top: 1%; the element is nearly in the right place, but I don't understand what it is basing that 1% off of and how to find that exact height?

Thanks!

maudulus
  • 10,627
  • 10
  • 78
  • 117
  • 1
    Regarding the `margin` property and a percentage value: [`The percentage is calculated with respect to the width of the generated box's containing block`](http://www.w3.org/TR/CSS2/box.html#margin-properties) - [Also, see this answer](http://stackoverflow.com/questions/11003911/why-are-margin-padding-percentages-in-css-always-calculated-against-width). [And this demo](http://jsfiddle.net/nvnofsgv/) – Nico O Aug 29 '14 at 15:20
  • 1
    On a slightly different note. What is actually happening has been told, so now you understand why what is happening is happening. Beyond that, I would suggest using em's for your margin-top/bottom on textual elements. (h1, h2, p, etc.) – Michael Aug 29 '14 at 15:21

1 Answers1

4

Margin percentages are weird in that margin-top and margin-bottom, when set as a percentage, are calculated by the browser based on the width of the containing element.

Don't believe me? I wouldn't blame you. Check out the article below or do a search on the topic.

http://www.impressivewebs.com/vertical-percentages-css/

p e p
  • 6,593
  • 2
  • 23
  • 32
  • Wow ok that is odd! I was thinking that there must be some extension to the page that I couldn't see, but it makes complete sense that the percentage that I originally set would be too high if the `margin-top` & `margin-bottom` is set based on page width. – maudulus Aug 29 '14 at 15:19
  • 1
    You are the quicker, either way, here is a JS Fiddle demo. Containing element is 200px wide, 10% evaluates to 20px of top margin, same as the div with 20px margin. Remove the container and scale the width of the JSFiddle window and watch the top margin of that element go up and down like crazy. http://jsfiddle.net/49b8noy6/ – Michael Aug 29 '14 at 15:19