CSS 流体布局:当容器宽度增加时,margin-top 基于百分比增长
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10629294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS fluid layout: margin-top based on percentage grows when container width increases
提问by Gregir
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.
我只是在学习 CSS 流体布局和响应式设计,我正在尝试在布局中使用没有 px 值的所有百分比值。
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?
到目前为止,它似乎正在起作用,但在一个地方,我看到了我没想到的东西。我试图在两个垂直堆叠的 div 之间放置一个边距,该边距会根据容器的高度而变化。我希望当我垂直调整窗口大小时,边距会改变,但如果水平调整它的大小,它也会增加,这是我不想要的。我错过了什么?
Here's a fiddle. Thanks for your help in advance.
这是一个小提琴。提前感谢您的帮助。
回答by Chuck Kollars
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.
在 CSS 中,所有四个 margin: 和 padding: 百分比都是相对于宽度的……尽管这可能看起来很荒谬。这就是 CSS 规范的方式,您对此无能为力。
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 suspectthe 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.)
你能用“ex”(或“em”)做你想做的吗?这就是我习惯于看到指定的边距/填充的“流动”值的方式......而且它可能比百分比问题少。(虽然我没有相关的第一手经验,但我怀疑你计算的百分比值的极长精度会让你以后遇到浏览器不兼容问题。我的风格是尽可能将 CSS 百分比限制为整数,或者有时可能是小数点后一位,有时甚至是两位数。)
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).
如果你真的想要一个精确的任意大小的垂直空白空间,它是容器的一个百分比,我想到的第一件事是一个单独的空 <div> 带有“高度:nn%”的 CSS 规范。或者您指定的其他东西可能已经按照您希望的方式处理垂直尺寸(因为看起来边距在垂直调整大小上根本没有做任何事情)。
回答by Mark M
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
是的,这是出乎意料和违反直觉的,但它按设计工作,我不知道为什么它会这样工作。当窗口高度降低时,查看margin-top百分比不会改变