jackarms
jackarms

Reputation: 1333

Flex box - arrange items in column with multiple elements on each row if space allows

I want to arrange some items of variable width in a column, where the column has a fixed width. But I want elements to stack up next to each other if the total width of a group of elements doesn't exceed the column width. In the snippet, I want to add CSS to the first container so that that the 2nd and 3rd divs will be next to each other, as they are in the second container. I don't know the element widths in advance so I can't just do this manually by putting divs around the elements that should be adjacent. I want to also accomplish with just flexbox, not CSS grids if that's also a solution.

.container {
  width: 500px;
  border: 1px solid red;
}

.flexcol {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.inlineblock > div {
  display: inline-block;
}

.item {
  border: 1px solid black;
  font-size: 24pt;
  text-align: center;
}

.item1, .item4 {
  width: 400px;
}

.item2, .item3 {
  width: 200px;
}
<div class="container flexcol">
  <div class="item item1">
    Item 1
  </div>
  <div class="item item2">
    Item 2
  </div>
  <div class="item item3">
    Item 3
  </div>
  <div class="item item4">
    Item 4
  </div>
</div>
<div class="container flexcol">
  <div class="item item1">
    Item 1
  </div>
  <div class="inlineblock">
    <div class="item item2">
      Item 2
    </div>
    <div class="item item3">
      Item 3
    </div>
  </div>
  <div class="item item4">
    Item 4
  </div>
</div>

Fiddle here of same code: https://jsfiddle.net/6ycer7b0/1/

Upvotes: 0

Views: 142

Answers (1)

Temani Afif
Temani Afif

Reputation: 272762

You can do this with a row direction and enable the wrap to simulate a column behavior as the elements will stack above each other:

.container {
  width: 500px;
  border: 1px solid red;
}

.flexcol {
  display: flex;
  flex-direction: row;
  flex-wrap:wrap;
  justify-content: center;
}

.item {
  border: 1px solid black;
  font-size: 24pt;
  text-align: center;
}

.item1, .item4 {
  width: 400px;
}

.item2, .item3 {
  width: 200px;
}
<div class="container flexcol">
  <div class="item item1">
    Item 1
  </div>
  <div class="item item2">
    Item 2
  </div>
  <div class="item item3">
    Item 3
  </div>
  <div class="item item4">
    Item 4
  </div>
</div>

Upvotes: 1

Related Questions