CSS fluid layout: margin-top based on percentage grows when container width increases [duplicate]

心已入冬 提交于 2019-11-27 02:31:14

问题


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/


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/10629294/css-fluid-layout-margin-top-based-on-percentage-grows-when-container-width-incr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!