如何防止动态宽度flexbox子项溢出父级?

时间:2017-09-21 06:12:58

标签: html css css3 flexbox

在下面的示例中,我想防止streched child溢出父级。我不想为它指定宽度。我怎么能做到这一点?

#flex-parent { display: flex; width: 200px; background: green; padding: 10px; }
#fixed-child { width: 20; background: red }
#stretched-child { background: yellow; word-wrap: break-word }
<div id="flex-parent">
  <div id="fixed-child">
FIXED
  </div>
  <div id="stretched-child">
  STREEEEEEEEEEEEEEEEEEEEEEEEEEEECHED
  </div>
</div>

1 个答案:

答案 0 :(得分:3)

您点击 min-width算法,其中Flex项的min-width默认为auto,因此不允许它缩小到其内容以下。

您可以使用word-break: break-all

#flex-parent {
  display: flex;
  width: 200px;
  background: green;
  padding: 10px;
}

#fixed-child {
  width: 20;
  background: red
}

#stretched-child {
  background: yellow;
  word-wrap: break-word;
  word-break: break-all;
}
<div id="flex-parent">
  <div id="fixed-child">
    FIXED
  </div>
  <div id="stretched-child">
    STREEEEEEEEEEEEEEEEEEEEEEEEEEEECHED
  </div>
</div>

min-width: 0允许它小于其内容

#flex-parent {
  display: flex;
  width: 200px;
  background: green;
  padding: 10px;
}

#fixed-child {
  width: 20;
  background: red
}

#stretched-child {
  background: yellow;
  word-wrap: break-word;
  min-width: 0;
}
<div id="flex-parent">
  <div id="fixed-child">
    FIXED
  </div>
  <div id="stretched-child">
    STREEEEEEEEEEEEEEEEEEEEEEEEEEEECHED
  </div>
</div>

经过快速的跨浏览器测试(Windows 10上的Chrome / Firefox / Edge / IE)后,IE显示需要word-break: break-alloverflow hidden