Search code examples
htmlcssflexboxcss-grid

Place elements side by side if they fit, else make them block elements


I have a bunch of pairs of elements. Each pair has two divs. I'd like each pair to sit side-by-side if they can fit on the same line, else I'd like them to sit one on top of the other. Here's the situation:

.pair {
  display: flex;
  flex-direction: row;
}

div {
  margin: 0 5px;
}
<div class="pair">
  <div>Yeet a deet</div>
  <div>Make me display:block when the container can't fit the divs side-by-side</div>
</div>

Without setting a breakpoint or using JS, is there a way to make these divs display: block when they can no longer fit side-by-side without wrapping? Any pointers would be very helpful!


Solution

  • Would flex-wrap not solve it?

    .pair {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .pair > * {
      box-shadow: 0 0 0 1px blue;
      flex: 1 1 auto;
    }
    
    div {
      margin: 0 5px;
    }
    <div class="pair">
      <div>Yeet a deet</div>
      <div>Make me display:block when the container can't fit the divs side-by-side</div>
    </div>