Search code examples
htmlcssflexboxalignmentword-wrap

CSS - How to force second div to another row when first div overflows


I have two divs placed next to each other of equal width. When the text in the first div overflows to a second line, I would like the second div to be placed below the first div- doubling the width of each div. Is this possible in CSS?

I have tried using flexboxes but I don't know where to go from here.

#container {
  display: flex;
  width: 500px;
  border: 1px solid black;
}

.cell {
  flex: 1;
}
<div id="container">
  <div class="cell" style="background-color:pink;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit
  </div>
  <div class="cell" style="background-color:lightblue;">
    Ut enim ad minim veniam, quis nostrud exercitation ullamco
  </div>
</div>


Solution

  • I figured it out. Both divs have to be min-width: 50% and the last div has to be flex: 1. The parent div should have flex-wrap: wrap.

    #container {
        display: flex;
        flex-wrap: wrap;
        width: 500px;
        border: 1px solid black;
    }
    #cell1 {
        background-color: pink;
        min-width: 50%;
    }
    #cell2 {
        background-color: lightblue;
        min-width: 50%;
        flex: 1;
    }
    <div id="container">
        <div id="cell1">
            Lorem ipsum dods Ut eniasdfasdf
        </div>
        <div id="cell2">
            Ut enim ad minim veniam, quis nostrud exercitation ullamco
        </div>
    </div>