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/
You can combine fixed value and percentage values in the CSS margin property. Negative values are allowed in the CSS margin property. When the value is provided as a percentage, it is relative to the width of the containing block. See also margin-top, margin-bottom, margin-left, and margin-right.
The [margin] percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1. ( emphasis mine)
The width and height properties include the content, padding, and border, but do not include the margin. Note that padding and border will be inside of the box.
Set the css property position:relative for parent of the container. Show activity on this post. Show activity on this post. Define some width on your container and set margin top & bottom to some desired value and left & right values to auto so that it will always split the remaining space on the both sides equally.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With