CSS3 flexbox layout max 3 child items on one line

后端 未结 6 1022
余生分开走
余生分开走 2021-02-07 03:05

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?

6条回答
  •  甜味超标
    2021-02-07 03:55

    Or you could use CSS Grid for this:

    Your HTML:

    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.

提交回复
热议问题