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

Time:12-02

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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!

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related