当窗口高度减小时,margin-top百分比不会改变

san*_*eep 11 css margin

我正在开发一个项目,客户希望导航<div>根据屏幕高度进行对齐,类似于margin-left屏幕宽度减小时百分比的工作方式.

所以,我给了margin-top: 20%导航<div>显示边距,但是当我减小窗口的高度时,它不会根据屏幕高度调整,尽管它在我减小屏幕宽度时起作用.

我的问题不是如何实现这一目标,而是为什么百分比水平而非垂直?

这是一个例子:http://jsfiddle.net/sandeep/5VReY/

Arj*_*jan 30

根据css规范,百分比适用于容器块的宽度

百分比是根据生成的框的包含块的宽度计算的.请注意,对于"margin-top"和"margin-bottom"也是如此.

有关更多信息,请参阅w3.org.

  • w3c中的男人抽烟喝什么?我无法相信清醒的人可以将margin-top和margin-bottom绑定到width而不是height. (39认同)

Vit*_*Rod 5

您可以在"自动"中播放具有边距道具的宽度顶部/底部属性;

如果您有这样的块:

<div class="centered"></div>
Run Code Online (Sandbox Code Playgroud)

它可能像Verticaly一样居中:

.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 */
}
Run Code Online (Sandbox Code Playgroud)

对于水平对齐宽度左/右属性,可以实现相同的效果.你也可以有一个偏移量来包含除块中心之外的其他点.

在这里,我给您一些结合这些属性的例子和方法. http://jsfiddle.net/SQDJ6/