How to prevent a dynamic width flexbox child from overflowing the parent?

后端 未结 1 877
一个人的身影
一个人的身影 2021-01-16 14:06

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?

相关标签:
1条回答
  • 2021-01-16 15:02

    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

    0 讨论(0)
提交回复
热议问题