搜索

首页  >  问答  >  正文

当父元素设置了min-height: 100%时,子元素不会继承高度

<p>我发现一种方法可以使一个div容器至少占据整个页面的高度,方法是设置<code>min-height: 100%;</code>。然而,当我添加一个嵌套的div并设置<code>height: 100%;</code>时,它并没有延伸到容器的高度。有没有办法修复这个问题?</p> <p><br /></p> <pre class="brush:css;toolbar:false;">html, body { height: 100%; margin: 0; } #containment { min-height: 100%; background: pink; } #containment-shadow-left { height: 100%; background: aqua; }</pre> <pre class="brush:html;toolbar:false;"><div id="containment"> <div id="containment-shadow-left"> Hello World! </div> </div></pre> <p><br /></p>
P粉517814372P粉517814372544 天前547

全部回复(2)我来回复

  • P粉799885311

    P粉7998853112023-08-22 14:22:28

    在父容器中添加height: 1px。在Chrome、FF和Safari中有效。

    回复
    0
  • P粉903052556

    P粉9030525562023-08-22 09:01:41

    这是一个已报告的webkit(chrome/safari)bug,具有最小高度的父元素的子元素无法继承height属性:https://bugs.webkit.org/show_bug.cgi?id=26559

    显然Firefox也受到影响(目前无法在IE中测试)

    可能的解决方法:

    • 在#containment中添加position:relative
    • 在#containment-shadow-left中添加position:absolute

    当内部元素具有绝对定位时,该bug不会显示。

    请参见http://jsfiddle.net/xrebB/

    2014年4月10日编辑

    由于我目前正在进行一个非常需要具有min-height的父容器和子元素继承容器高度的项目,所以我进行了更多的研究。

    首先:我不再确定当前浏览器行为是否真的是一个bug。CSS2.1规范说:

    如果我在容器上设置了min-height,我并没有明确指定其高度 - 所以我的元素应该获得一个auto高度。这正是Webkit - 和所有其他浏览器 - 所做的。

    其次,我找到的解决方法:

    如果我将容器元素设置为display:table并使用height:inherit,它的行为与给它一个min-height为100%完全相同。而且 - 更重要的是 - 如果我将子元素设置为display:table-cell,它将完美地继承容器元素的高度 - 无论是100%还是更多。

    完整的CSS:

    html, body {
      height: 100%;
      margin: 0;
    }
    
    #container {
      background: green;
      display: table;
      height: inherit;
      width: 100%;
    }
    
    #content {
      background: red;
      display: table-cell;
    }

    标记:

    <div id="container">
      <div id="content">
          <p>content</p>
      </div>
    </div>

    请参见http://jsfiddle.net/xrebB/54/

    回复
    0
  • 取消回复