How to display 3 items per row in flexbox?
Solution 1:
Flex container:
- You probably want to use
display: flex
notinline-flex
. - Add
flex-wrap: wrap
to allow wrapping onto multiple lines. - Remove
width: 33%
if you wish it to take entire space avaiable.
For 3 items per row, add on the flex items:
flex-basis: 33.333333%
- You can also use the
flex
's shorthand like the following:flex: 0 0 33.333333%
=> which also meansflex-basis: 33.333333%
.
.serv ul {
display: flex;
flex-wrap: wrap;
padding-left: 0;
}
.serv ul li {
list-style: none;
flex: 0 0 33.333333%;
}
<div class="serv">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
Solution 2:
I had this same issue, but the selected correct answer did not work cause the my child items needed to have a fix width so here is my solution to show X items of fix width on DISPLAY: FLEX.
// Flex item width required: 215px
// Flex item margin 20px on each side: 215px + 20 + 20 = 255px
// I needed 3(your item per row) so: 255px * 3
// Then to (100% of parent-flex minus 255 * 3) / 2 padding on each side
// So it stays in the center.
padding: 40px calc((100% - (255px * 3)) / 2);
*, *::before, *::after {
box-sizing: border-box;
}
.parent-flex {
display: flex;
flex-wrap: wrap;
justify-content: center;
background-color: tomato;
padding: 40px calc((100% - (255px * 3)) / 2);
}
.flex-item {
height: 100px;
flex: 0 0 215px;
margin: 1em 20px;
border: 2px blue solid;
}
<div class="parent-flex">
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
</div>
Solution 3:
body {
margin: 0px;
}
.parent {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.flex-item{
/*
All you need to do this play with this number (343) according to aviable width and item width
Formula: (ParentWidth / 3) - margin (ParentWidth divide by 3 subtracte by margin[if you want e.g in my case i set 10] )
Stackoverflow Run Code Snippet width = 633.82px (not sure)
Margin = 10px
*/
flex: 0 0 192px; /* play with this number */
background: red;
margin: 10px;
}
<div class="parent">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
<div class="flex-item">6</div>
<div class="flex-item">7</div>
<div class="flex-item">8</div>
<div class="flex-item">9</div>
<div class="flex-item">10</div>
</div>