css - 高度 : 100vh (working) vs min-height: 100vh (not working) for body? 背后的技术原因

标签 css

请不要投票关闭。这是关于为什么这不起作用的技术原因。我已经有一个可行的解决方案,我不会要求它。

我需要制作 .wrapper 高度的简单示例,至少是浏览器高度。

以下适用于 IE10-11、Edge、Firefox、Chrome ( working fiddle ):

<!doctype html>
<html lang="it">
    <head >
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Demo</title>
        <style>
            body {
                margin: 0;
                height: 100vh;
                background-color: red;
            }

            .wrapper {
                min-height: 100%;
                background-color: green;
            }
        </style>
    </head>
    <body>
        <div class="wrapper"></div>
    </body>
</html>

但是如果我将 body 设置为 min-height 而不是 height (恕我直言,这是合理的),它就不起作用不再(not working fiddle)。为什么?其背后的技术原因是什么?

编辑 1

Another working fiddle其中 bodymin-height: 100vh.wrappermin-height: inherit

Another working fiddle只有 .wrappermin-height: 100vh

最佳答案

CSS 2.2 spec says :

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

这就是规则。规则背后的原因很简单,遵循 CSS 2 中的类似规则,必须避免循环依赖。

指定容器的高度时,它不依赖于其内容的高度,因此可以安全地将其内容的高度指定为高度的百分比,而不会产生循环依赖。

但这不适用于仅指定容器的最小高度的情况。如果内容的高度大于最小高度,则容器的高度取决于内容的高度,如果是百分比,则内容的高度取决于容器的高度,这就是循环依赖。所以它故意“不起作用”,以阻止这种情况的发生。

关于css - 高度 : 100vh (working) vs min-height: 100vh (not working) for body? 背后的技术原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395367/

相关文章:

css - 垂直对齐图像,文本,图像在CSS中的div内

html - CSS:如何更改代码中的位置或索引

jquery - 如何使用 jquery 获取最后一个通用子节点?

javascript - jquery 选择器从表中访问 anchor

css - 丢失了我的 <div id=header> 从 HTML 5 切换到 XHTML 1 Transitional

CSS3 倾斜技巧

javascript - 除了具有 float 和中心的 div 类之外布局 div

html - 如何使 float 扩展宽度?

html - 仅当跨度位于 <a> 中且类不为 "folder"时,如何才能使我的 CSS 工作?

javascript - 表头上的切换按钮仅在 2 次切换后才有效