This question already has an answer here:
-
How to set the margin or padding as percentage of height of parent container?
8 answers
I'm just learning CSS fluid layouts & responsive design, and I'm trying to use all percentage values with no px values in a layout.
So far it seems to be working, but in one spot, I'm seeing something I didn't expect. I'm trying to put a margin between two vertically stacked divs that changes based on the height of the container. I'd expect that margin to change when I resize the window vertically, but it also grows if you resize it horizontally, which I don't want. What am I missing?
Here's a fiddle. Thanks for your help in advance.
http://jsfiddle.net/gregir/aP5kz/
In CSS, all four margin: and padding: percentages are relative to the width ...even though that may seem nonsensical. That's just the way the CSS spec is, there's nothing you can do about it.
Can you do what you want with 'ex' (or 'em') instead? That's the way I'm used to seeing "fluid" values for margin/padding specified ...and it may be less problematic than percentages. (Although I don't have the relevant first-hand experience, I suspect the extremely long precisions on your calculated percentage values are going to set you up for browser incompatibility problems later. My style is to limit CSS percentages to integers if at all possible, or occasionally perhaps one or sometimes maybe even two digits after the decimal point.)
If you really want an exact arbitrarily-sized empty vertical space that's a percentage of the container, the first thing that comes to my mind is a separate empty < div > with a "height: nn%" CSS specification. Or perhaps something else you're specifying is already handling the vertical sizes they way you wish (since it would appear the margins aren't really doing anything at all on a vertical resize).
Yes, it is unexpected and counter-intuitive, but it works as designed & I have no idea why it works as it does. See margin-top percentage does not change when window height decreases