在Safari中Flex容器溢出容器

时间:2017-09-13 16:46:54

标签: html css css3 safari flexbox

出于某种原因,Flex项目不会停留在Safari中的容器内。

以下是Chrome和Firefox中的布局:

enter image description here

以下是Safari中的样子:

enter image description here

这是我的代码:

#div1 {
  background: black;
  width: 250px;
  height: 600px;
  display: flex;
  flex-direction: column;
  padding-bottom: 5px
}

#div2 {
  background: pink;
  color: #FFF;
  width: 240px;
  height: 200px
}

#div3 {
  background: blue;
  color: #FFF;
  width: 240px;
  height: 100%;
  position: relative
}
<div id="div1">
  <div id="div2">test</div>
  <div id="div3">test2</div>
</div>

1 个答案:

答案 0 :(得分:2)

问题

您有一个height: 600px的容器。

这个容器有两个孩子:

  • 一个孩子有height: 200px
  • 另一个孩子有height: 100%

由于百分比高度基于父级的高度,因此您将第二个子级的高度设置为等于容器的整个高度。

  

10.5 Content height: the height property

     

<强>百分比

     

指定百分比高度。百分比是根据生成的框的包含块的高度计算的。

结果发生溢出:

(200px + 600px) > 600px

除了在Flex容器中,初始设置为flex-shrink: 1。这意味着flex项目可以缩小以适合容器内部。 Chrome和Firefox正确应用此设置,允许height: 100%元素缩小以适应。 Safari显然有不同的解释。

解决方案

您可以使用calc()来解决问题:

#div3 {
  height: calc(100% - 200px);
}

#div1 {
  background: black;
  width: 250px;
  height: 600px;
  display: flex;
  flex-direction: column;
  padding-bottom: 5px
}

#div2 {
  background: pink;
  color: #FFF;
  width: 240px;
  height: 200px
}

#div3 {
  background: blue;
  color: #FFF;
  width: 240px;
  height: calc(100% - 200px);
}
<div id="div1">
  <div id="div2">test</div>
  <div id="div3">test2</div>
</div>

但是,由于您已经在列方向灵活容器中工作,因此可以使用flex使第二个子节点占用剩余空间:

#div3 {
  flex: 1;
}

这意味着:这个孩子将消耗任何未被其他兄弟姐妹消耗的空间。

#div1 {
  background: black;
  width: 250px;
  height: 600px;
  display: flex;
  flex-direction: column;
  padding-bottom: 5px
}

#div2 {
  background: pink;
  color: #FFF;
  width: 240px;
  height: 200px
}

#div3 {
  background: blue;
  color: #FFF;
  width: 240px;
  flex: 1;
}
<div id="div1">
  <div id="div2">test</div>
  <div id="div3">test2</div>
</div>