Arrange 2 items per row using flexbox

HtmlCssFlexbox

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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>

Solution 2 - Html

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

Solution 3 - Html

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPranavPinarayiView Question on Stackoverflow
Solution 1 - HtmldippasView Answer on Stackoverflow
Solution 2 - HtmlDeepak TerseView Answer on Stackoverflow
Solution 3 - HtmlBenView Answer on Stackoverflow