Percentage based margin-top and height are not working together
Here’s the JSFiddle link. And here’s the CSS code:
I’ve been making a page with 4 elements, and the problem I’ve encountered is that when resizing the browser window, the width of the elements (and the margin between them) change as I expect, but for some reason, the elements can start overlapping vertically, even though, for example, the height of the black element (div class a) is 13%, the height of the green element is 86 (div class c)%, and the green element has an absolute position and margin-top value of 14%.
The blue element (div class d) can become positioned lower than the browser window’s lower edge (even though it has a margin-top of 87% and a height of 13%, it seemed logical to me that it would be situated at the very bottom of the window; not higher or lower).
What is going on? I wanted the elements to be positioned exactly at the edges of the browser window, resize automatically on window size change and not overlap). I planned on using jQuery to make the vertical and horizontal margins match. But now, I need to understand why my CSS code isn’t working as expected.
If you’re looking for a reason as to why this behavior is occurring:
Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block , not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).
Emphasis added. These
margin-top values are relative to the width of the
body element. In this instance, if the window is resized horizontally, the heights of the elements don’t change, yet the
margin-top values do; resulting in vertical alignment issues.
No need to use jQuery to solve this. The solution would be to use something other than margins for displacement. See this updated example.