【问题标题】:Percentage height not working in nested flexbox layout in Chrome百分比高度在 Chrome 的嵌套 flexbox 布局中不起作用
【发布时间】:2015-09-11 20:09:35
【问题描述】:

我有一个完全在 Firefox 和 IE 中工作的布局:

不幸的是,它在 Chrome 中被破坏了,即深蓝色容器即使其高度是其父级的 100% 也已折叠:

我试过this approach,但没有任何运气。任何想法如何在 Chrome 上解决此问题而不在其他浏览器中破坏它?

html,
body {
  height: 97%;
  margin: 0;
  padding: 0;
}

div {
  border: 10px dotted teal;
}

.container {
  display: flex;
  border-color: tomato;
  height: 100%;
}

.row {
  flex-flow: row;
}

.column {
  flex-flow: column;
}

.item1 {
  flex: 1;
}

.item2 {
  flex: 2;
}

.item3 {
  flex: 3;
}

.c1 {
  border-color: gold;
}

.c2 {
  border-color: darkblue;
}
<div class="container">
  <div class="item3">
    <div class="container column c2">
      <div class="item1 c1"></div>
      <div class="item3"></div>
    </div>
  </div>
  <div class="item1 c1"></div>
  <div class="item2"></div>
</div>

【问题讨论】:

    标签: html css google-chrome flexbox


    【解决方案1】:

    问题说:

    我有一个完全在 Firefox 和 IE 中工作的布局。 不幸的是它在Chrome中坏了,即深蓝色 即使容器的高度是其父容器的 100%,它也会折叠。

    实际上,可以提出相反的说法:Chrome 是正确的,而 Firefox 和 IE 是“坏掉的”。

    首先,解决方案如下:

    .item3 { height: 100%; }
    

    现在让我们看看您的文档结构和应用的高度:

    <html> <!-- height: 97% -->
    <body> <!-- height: 97% -->
    <div class="container"> <!-- height: 100%; -->
        <div class="item3"> <!-- height: ?? -->
            <div class="container column c2"> <!-- height: 100% ; this is the collapsed box -->
                           ...
                           ...
                           ...
    

    根据CSS specification,当使用百分比设置元素的height 时(就像您对.container 所做的那样),父元素必须 也有明确的高度。参考您折叠的div,其父级 (.item3) 没有定义的高度。

    来自spec


    百分比是相对于高度计算的 生成框的包含块。如果高度 包含块未明确指定(即,它取决于 内容高度),并且该元素不是绝对定位的, 值计算为“自动”。

    auto
    高度取决于其他属性的值。

    height 属性而言,从这个例子中可以看出,Chrome 将“包含块”定义为“父级”,而 Firefox 和 IE 将“包含块”定义为“祖先”,或者它们将 flex 高度定义为百分比高度的参考。

    因此,由于带有深蓝色边框 (.container column c2) 的 div 没有内容,并且其父级没有指定高度,因此在 Chrome 中没有高度并且框折叠。

    但是,通过为 .item3(折叠框的父级)指定高度,该高度适用于所有浏览器。

    DEMO


    更新

    更多细节:

    【讨论】:

    • 哦,我完全忘记了这个问题(真丢脸),我已经在 GitHub 上的 Angular Material 票证中解决了这个问题。但是我相信这也会帮助其他一些人(或者可能是未来的我)。感谢您的详尽回答。
    猜你喜欢
    • 2011-09-06
    • 2013-05-14
    • 2017-12-28
    • 2017-09-27
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2012-03-22
    相关资源
    最近更新 更多