【问题标题】:children of min-height:100% do not apply height:100%最小身高的孩子:100% 不适用身高:100%
【发布时间】:2014-03-31 03:58:05
【问题描述】:

我想要一个 height:100% 的子元素;容器应用高度:100%;。当存在 doctype 时,这似乎失败了。

如果你使用 min-height:100%;对于父元素,子元素不应用 height:100%;。

如果你使用 height:100%;子元素被拉伸,但会溢出父元素。 如果您尝试使用 height:100%;在父节点上并保持最小高度:100%;在孩子身上,孩子们不会再伸懒腰了。

这里有一个小例子:

<!DOCTYPE html>
<html>
<head>
<title>Oh Well</title>
<style>
html, body {
    width: 100%;
    height:100%;
    background: white;
    margin:0;
    padding:0;
}

#min-h-100 {
    background-color: #eee;
    min-height: 100%;
}
#min-h-100 > div{
    min-height: 100%;
}

#h-100 {
    background-color: #ccc;
    height: 100%;
}
#h-100 > div {
    height: 100%;
}
</style>
</head>
<body>
<div id="min-h-100">
   <div>If this is heigher than the container, the container expands.</div>
   <div>The child elements do not get 100% height.</div>
</div>
<div id="h-100">
    <div>The child elements get 100% height.</div>
    <div>But there will be an overflow.</div>
</div>
<div>THIS SHOULD BE PUSHED DOWN</div>
</body>
</html>

编辑: min-height 不继承。 @GCryrillus 提出了将 display:table 应用于父级的想法,这至少可以扩展父级。 @Volker E. 创建了一个codepen

编辑: 如果不想支持IE≤8,可以设置child min-height:100vh;这将使其至少与视口一样高。

【问题讨论】:

  • min-height 不能被 min-height 继承,也不能被任何其他规则继承。 规则仅继承自父级中的相似规则
  • @GCyrillus 所以这就是为什么 min-height 不起作用,谢谢:)。有没有办法防止溢出,或者在使用 height:100%; 时拉伸父级?
  • 您可以尝试将height:100% 发送给所有孩子并使用display:table,这样可以让他们伸展,然后您还需要设置width
  • 那也没用 :(。感谢您的快速回复!
  • 你能在网上做一个小提琴或一个codepen,看看你是如何设置这些规则的吗?

标签: css html height


【解决方案1】:

我觉得这个问题很有趣,尤其是案例 #2,id="h-100" 暗示 height: 100% 父母上有几个 height: 100% 孩子。

我想出了一个Codepen including the different options。 为防止第二种情况溢出,您也可以使用overflow: hidden,但这会导致信息丢失。

@GCyrillus 说的对,使用display: table;display: table-row/table-cell; 符合孩子divs。

#h-100-table {
    background-color: #ddd;
    display: table;
    width: 100%;
    height: 100%;
}
#h-100-table > div {
    display: table-row;
    width: 100%;
}
#h-100-table > div > div { // you don't need to go for extra nesting, but it's clearer.
    display: table-cell;
    width: 100%;
}

#h-100-table 的孙子不是必需的,更多的是为了可维护性。你也可以和table-rowchildren 一起去。

【讨论】:

  • @GCyrillus 用你的方法让父母伸展,但第二个孩子似乎只是显示非空白区域。
【解决方案2】:

如果不想支持IE≤8,可以设置child min-height:100vh;这将使其至少与视口一样高(因此基本上会给您想要的效果)。 (seen here)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2012-04-22
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多