【问题标题】:Firefox ignoring min-height in CSSFirefox 忽略 CSS 中的最小高度
【发布时间】:2016-01-13 12:28:46
【问题描述】:

由于某种原因,min-height 不适用于 Firefox。我尝试在身体上设置最小高度,但 Firefox 完全忽略了它。由于我的页面是动态的,我不能只将高度设置为 100%。我该怎么办?

body {
border: 1px solid black;
width: 100%;
min-height: 100%;
}
<body>

This is the body.

</body>

【问题讨论】:

  • height 百分比适用于绝对定位的元素。如果您需要它以百分比形式提供,请将 position:absolute; 添加到 body 样式
  • @SaqibAmin min-height 在谷歌浏览器中运行良好。
  • 我刚刚在一个空文档上重新确认了样式,您必须添加 position:absolute; 才能使其按您希望的方式工作
  • @SaqibAmin height 不需要position: absolute; 才能工作。你在哪里读到的?
  • @SaqibAmin 仅当包含块没有设置高度时。我在答案中添加了绝对方法,并提供了有关您的意思的更多信息

标签: html css firefox height document-body


【解决方案1】:

height 百分比是继承的(也包括min-height and max-height)。来自 CSS 规范:

指定用于确定使用值的百分比。 百分比是相对于生成框的包含块的高度计算的

大多数人没有意识到body 和其他元素一样只是一个元素,html 也是如此。人们还没有意识到这些元素没有固有的高度设置。 html 的父级是视口,它确实具有 100% 的固有高度。视口或多或少是浏览器窗口,减去任何菜单或标题栏。

由于height 百分比从其父级继承,并且您没有为html 元素设置height,因此min-height: 100%; 的CSS 没有取100% 的值。所以你的身体基本上是 0 的min-height: 100%

要解决此问题,只需告诉您的 html 元素为视口高度的 100%:

html {
    height: 100%; /* this is the important bit */
}

body {
    border: 1px solid black;
    width: 100%;
    min-height: 100%;
    margin: 1px; /* I added this to make the border around the body a little easier to see. Normally you want to set it to 0 or leave it alone completely */
}
<body>
This is the body.
</body>

但是,如果您不想将整个文档设置为与视口一样高(我强烈建议您这样做),您还可以在 body 元素上使用 position: absolute;,以便百分比高度将始终解析,无论其父元素的高度如何。这就是 Saqib 在上面的 cmets 中试图达到的目的。分别来自关于最小高度和高度的 CSS 规范:

如果包含块的高度没有明确指定(即它取决于内容高度),并且该元素不是绝对定位的,则百分比值被视为'0'(对于'min-height')或“无”(代表“最大高度”)。

-

请注意,绝对定位元素的包含块的高度与元素本身的大小无关,因此始终可以解析此类元素的百分比高度。

body {
    border: 1px solid black;
    width: 100%;
    min-height: 100%;
    position: absolute;
    margin: 1px; /* I added this to make the border around the body a little easier to see. Normally you want to set it to 0 or leave it alone completely */
}
<body>
This is the body.
</body>

(我不知道您的哪些代码在 Chrome 中运行,但您问题中的代码在 Chrome 中的行为与在 Firefox 中的行为相同。)

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 2013-08-10
    • 2021-11-10
    • 2016-02-24
    • 2013-12-28
    • 2011-04-24
    • 1970-01-01
    • 2012-10-24
    • 2012-11-06
    相关资源
    最近更新 更多