CSS 当窗口高度降低时,margin-top 百分比不会改变
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7266363/
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
margin-top percentage does not change when window height decreases
提问by sandeep
I am working on a project in which the client wants the navigation <div>
to align according to the screen height, similar to how margin-left
as a percentage works when screen width is decreased.
我正在做一个项目,客户希望导航<div>
根据屏幕高度对齐,类似于margin-left
屏幕宽度减小时百分比的工作方式。
So, I gave margin-top: 20%
and navigation <div>
displays that margin, but when I decrease the height of the window it does not adjust according the screen height although it works when I decrease the screen width.
所以,我给margin-top: 20%
和导航<div>
显示了那个边距,但是当我减小窗口的高度时,它不会根据屏幕高度进行调整,尽管它在我减小屏幕宽度时可以工作。
My question is not howcan I achieve that, but why does the percentage work horizontally and not vertically?
我的问题不是我怎样才能做到这一点,而是为什么百分比是水平工作而不是垂直工作?
Here is an example: http://jsfiddle.net/sandeep/5VReY/
这是一个例子:http: //jsfiddle.net/sandeep/5VReY/
回答by Arjan
The percentage works on the width of the container block, according to the css specifications
根据 css 规范,百分比适用于容器块的宽度
The 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.
百分比是根据生成的框的包含块的宽度计算的。请注意,对于“margin-top”和“margin-bottom”也是如此。
See w3.orgfor more information.
有关更多信息,请参阅w3.org。
回答by Viter Rod
You can play width top/bottom properties having margin prop in "auto";
您可以在“自动”中播放具有边距属性的宽度顶部/底部属性;
If you have a block like this:
如果您有这样的块:
<div class="centered"></div>
It may be centered verticaly like this:
它可能像这样垂直居中:
.centered {
width: 100px; height: 100px; /* must be present. No matter the value */
position: absolute; /* to props top/bottom take effect */
margin: auto; /* here's the magic. */
bottom: 0px; top: 0px; /* This is how you center a block verticaly */
}
The same can be achieved for horizontal alignment width left/right properties. You can also have an offset in order to ubicate other point than the center of the block.
对于水平对齐宽度左/右属性也可以实现相同的效果。您还可以有一个偏移量,以便对块中心以外的其他点进行 ubicate。
Here I leave you some examples of what and how can be done combining these properties. http://jsfiddle.net/SQDJ6/
在这里,我给你留下了一些关于结合这些属性可以做什么和如何做的例子。 http://jsfiddle.net/SQDJ6/