How to prevent a dynamic width flexbox child from

2020-03-30 11:11发布

In the sample below, I want to prevent the streched child from overflowing the parent. I do not want to specify a width for it. How can I accomplish that?

#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>

标签: html css flexbox
1条回答
神经病院院长
2楼-- · 2020-03-30 11:19

You hit the min-width algorithm, where the min-width of a flex item defaults to auto and as such doesn't allow it to shrink below its content.

You can use 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>


Or min-width: 0 to allow it to be smaller than its content

#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>


After a quick cross browser test (Chrome/Firefox/Edge/IE on Windows 10), it appears IE need either the word-break: break-all or overflow hidden

查看更多
登录 后发表回答