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

Cof*_*ite 1 html css flexbox

在下面的示例中,我想防止拉伸的孩子溢出父级。我不想为其指定宽度。我怎样才能做到这一点?

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

LGS*_*Son 5

您点击了min-width algorithm,其中min-widthflex 项目的默认值为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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="flex-parent">
  <div id="fixed-child">
    FIXED
  </div>
  <div id="stretched-child">
    STREEEEEEEEEEEEEEEEEEEEEEEEEEEECHED
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


或者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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="flex-parent">
  <div id="fixed-child">
    FIXED
  </div>
  <div id="stretched-child">
    STREEEEEEEEEEEEEEEEEEEEEEEEEEEECHED
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


一个快速的跨浏览器测试之后(浏览器/火狐/ EDGE / IE在Windows 10),它似乎IE需要无论是word-break: break-alloverflow hidden

  • `min-width: 0` 救了我的命 (3认同)