PranavPinarayi
PranavPinarayi

Reputation: 3207

Arrange 2 items per row using flexbox

Imagine I have following markup

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

and style

.item {
  width: 100%
}

and due to certain reasons I can't change the width of the .item Can I arrange 2 items in each row by styling parent container .container, using flexbox or any other way?

Upvotes: 145

Views: 358856

Answers (3)

dippas
dippas

Reputation: 60543

You can give flex: 50% to children divs without touching .item

.item {
  width: 100%
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > div {
  flex: 50%; /* or - flex: 0 50% - or - flex-basis: 50% - */
  /*demo*/
  box-shadow: 0 0 0 1px black;
  margin-bottom: 10px;
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

Upvotes: 308

Deepak Terse
Deepak Terse

Reputation: 712

The below solution worked for me

.parent{
  display: flex;
  flex-wrap: wrap;
}

.child{
  width: 25%;
  box-sizing: border-box;
}

Sample: https://codepen.io/capynet/pen/WOPBBm

Upvotes: 9

Ben
Ben

Reputation: 2209

Assuming that the width property must not be changed, I can think of a few possible solutions, the first being fit-content which has amazingly poor browser support. The second, is use positioning, which is an equally bad idea due to its finicky nature and likelihood to fail on different screen sizes.

Now the last two, are very similar, one is to use two containers, give them display:inline; give them a limited width, and fill them with items. If you didn't notice, this is essentially a 2×1 table.

Lastly you could make a 2×1 table, and while it is probably the easiest solution here, it is a bad idea to get in the habit of using tables to position things other than forms and tables. However, it is an option that I will make available to you.

Good luck!

Upvotes: 0

Related Questions