CSS3 flexbox layout max 3 child items on one line

后端 未结 6 1025
余生分开走
余生分开走 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:45

    Instead of using display: flex you could use float: left and clear every 3rd child node like this:

    .child {
        background: #000;
        height: 300px;
        float: left;
        margin:15px 0 0 15px;
        width:150px;
    
    }
    .child:nth-child(3n+1) {
        clear: left;   
    }
    

    I created a fiddle for you: fiddle example

    In the case that the parent can hold only two children, you could use this short jQuery fix:

    var child = $('.child'),
        parent = $('.child').parent();
    
    if( child.width() > (parent.width()/3) ) {
         child.css('clear', 'none');   
    }
    

    Fiddle with fix: fiddle example2

提交回复
热议问题