Search code examples
cssflexboxwidth

flexbox item 100% of remaining width


I want to achieve the following scenario with flexbox

enter image description here

the green element is a text element and the width is flexible. The blue elements should have 100% of the remaining width beside the green element.

My current solution looks like this:

<div class="container">
  <span class="title">title</span>
  <div class="fullwidth"></div>
  <div class="fullwidth"></div>
  <div class="fullwidth"></div>
</div>

and the css:

.container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background-color: #EAEBEF;

  .title {
    padding: 20px;
    background-color: #48CFAE;
  }

  .fullwidth {
    background-color: #87BDFF;
    flex: 0 0 100%;
    height: 60px;
    margin: 10px 0;
  }
}

But it looks currently like this current state here is a codepen example


Solution

  • Without changing the HTML this can be managed with CSS-Grid as an alternative to flexbox.

    .container {
      display: grid;
      grid-template-columns: max-content 1fr;
      grid-gap: 1em;
      background-color: #EAEBEF;
      margin-bottom: 1em;
    }
    
    .title {
      padding: 10px;
      grid-row: 2;
      background-color: #48CFAE;
    }
    
    .fullwidth {
      grid-column: 2;
      background-color: #87BDFF;
      height: 40px;
    }
    <div class="container">
      <div class="title">title</div>
      <div class="fullwidth"></div>
      <div class="fullwidth"></div>
      <div class="fullwidth"></div>
    </div>
    
    <div class="container">
      <div class="title">Longer title</div>
      <div class="fullwidth"></div>
      <div class="fullwidth"></div>
      <div class="fullwidth"></div>
    </div>