Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 flexbox layout max 3 child items on one line

Tags:

Is their an simple way in CSS to have a fixed maximum of child items on the same line, before you push the next child elements to a new line?

flex wrapper with four child items

As i understand flexbox, child items only get pushed to a new line if their isint enough available space on the line above it. But i am seeking a CSS rule or function that let me say "i want a maximum of 3 child items on any given line, and even if space is available for a 4'th one push it to a new line".

like image 721
Cristian Matthias Ambæk Avatar asked Jan 05 '15 16:01

Cristian Matthias Ambæk


People also ask

How do you flex 3 items per row?

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 means flex-basis: 33.333333% .

Which flex-wrap value will allow my flex items to all stay in one line?

nowrap: The default value of wrap-flex is nowrap. It is used to specify that the item has no wrap. It makes item wrap in single lines.

What are the disadvantages of using flexbox?

One of the major drawbacks of using flexbox is performance issues. The use of flexbox can increase the page loading time if you have a larger project. You can compare the page loading time through Chrome development tools using the flexbox and the same pages constructed without using flexbox.


2 Answers

Use flex-basis.

.child {
flex-basis: 33%;
}

The percentage must be adapted according to you box-sizing model, and the use of margins and/or padding.

like image 93
wout Avatar answered Oct 03 '22 03:10

wout


Or you could use CSS Grid for this:

Your HTML:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

Your CSS:

.parent {
    display: grid; // activate grid
    grid-template-columns: repeat(4, 1fr); //make 4 cols with size 1fr
    grid-gap: 20px; //gap between the rows
}
.child { //thats written with less. Just unnest for vanilla css
    &:nth-child(3n+1) {
      grid-column: 1;
    }
    &:nth-child(3n+2) {
      grid-column: 2;
    }
    &:nth-child(3n+3) {
      grid-column: 3;
    }
    &:nth-child(3n+4) {
      grid-column: 1; //put the fourth item in a new row
    }
}

I'm sure there are more efficient ways to write this with grid. But this does the job.

like image 24
KSPR Avatar answered Oct 03 '22 04:10

KSPR