Search code examples
htmlcssflexbox

Flex grow not using space when one of the children is wrapped


In the following code, I would like to have the 2nd child (single line, never wrap) to use all available space.

In example 1, that works well.

But when the first child wraps due to lack of space in example 2, there is a large gap between the two children. How can I remove that large gap that appears only when the first child content wraps?

.container {
margin-bottom:1rem;
background-color:#eee;
display:flex;
gap:1rem;
align-items:center;
}

.container>span:nth-child(1) {
  
}

.container>span:nth-child(2) {
white-space:nowrap;
flex:1 1 auto;
}
Example 1:
<div class="container"  style="width:500px;">
  <span>text allowed to be multilineeeeeeee</span>
  <span>single line</span>
</div>

Example 2:
<div class="container" style="width:250px;">
  <span>text allowed to be multilineeeeeeee</span>
  <span>single line</span>
</div>


Solution

  • flex: 1 1 min-content;

    This should get you close but note that it's just not possible to completely collapse the containing span when the text wraps. There is always space to the right on a wrap be it text or inline (or inline-block) elements wrapping.

    .container {
      margin-bottom: 1rem;
      background-color: #eee;
      border: 1px solid green;
      display: flex;
      gap: 1rem;
      align-items: center;
    }
    
    .container * {
      border: 1px solid red;
    }
    
    .container>span:nth-child(1) {
      flex: 1 1 min-content;
    }
    
    .container>span:nth-child(2) {
      white-space: nowrap;
      flex: 1 1 auto;
    }
    Example 1:
    <div class="container" style="width:500px;">
      <span>text allowed to be multilineeeeeeee</span>
      <span>single line</span>
    </div>
    
    Example 2:
    <div class="container" style="width:250px;">
      <span>text allowed to be multilineeeeeeee</span>
      <span>single line</span>
    </div>