Search code examples
htmlcssflexbox

Setting flex container to content width


I thought this was simple but I can't get is right. I have a .notes-container. The width should be set by the content of the .first-line. And the the .second-line should take the same width. The width of .notes-container should not be set but adjust to .first-line. The problem is to let the .second-line adjust to the .first-line width.

.notes-container {
  display: flex;
  flex-direction: column;
}

.first-line {
  display: flex;
  flex-direction: row;
}

.second-line {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-grow: 1;
}
<div class="notes-container">

  <div class="first-line">
    <div>content 1</div>
    <div>content 2</div>
    <div>content 3</div>
    <div>content 4</div>
  </div>

  <div class="second-line">
    <div>content 5</div>
    <div>content 6</div>
    <div>content 7</div>
  </div>

</div>

Any idea how to solve this?


Solution

  • In .notes-container, switch from display: flex to display: inline-flex.

    The former takes up all available space in the row.

    The latter adjusts to the width of the content.

    .notes-container {
      display: inline-flex; /* adjusted */
      flex-direction: column;
    }
    
    .first-line {
      display: flex;
    }
    
    .second-line {
      display: flex;
      justify-content: space-between;
      flex-grow: 1;
    }
    <div class="notes-container">
    
      <div class="first-line">
        <div>content 1</div>
        <div>content 2</div>
        <div>content 3</div>
        <div>content 4</div>
      </div>
    
      <div class="second-line">
        <div>content 5</div>
        <div>content 6</div>
        <div>content 7</div>
      </div>
    
    </div>