Make flex items wrap in nested flex containers before containers themselves wrap in main container

前端 未结 1 1398
青春惊慌失措
青春惊慌失措 2021-02-19 09:39

If I have a flexbox container containing multiple containers, how do I make the containers\' contained items wrap before the containers themselves?

For example (codepen)

相关标签:
1条回答
  • 2021-02-19 10:21

    I don't believe there are any flex properties that make this process simple and easy. However, the flexbox specification does allow for absolutely-positioned flex children. So with a combination of media queries and absolute positioning, the flex items within the container can be made to wrap before the container itself wraps.

    Try this:

    HTML (no changes)

    CSS (add media queries and absolute positioning)

    #second { position: relative; } 
    /* establishes nearest positioned ancestor for absolute positioning */
    
    @media screen and (max-width: 1000px) { 
        #second widget:nth-child(3) { 
            position: absolute; 
            left: 0; 
            bottom: 0; 
            width: 90%; }
        }
    
    @media screen and (max-width: 800px) {  
        #second { height: 375px; }
        #second widget:nth-child(2) { 
            position: absolute; 
            left: 0; 
            bottom: 127px; 
            width: 75%; }
        #second widget:nth-child(3) { 
            position: absolute; 
            left: 0; 
            bottom: 0; 
            width: 75%; }   
        }
    
    /* final media query removes absolute positioning and restores flex properties */       
    @media screen and (max-width: 600px) {  
        column, row, widget { flex-wrap: wrap; }
        #second widget {
            position: static;
            width: calc(25% - 3em);
            min-width: 300px;
        }
    

    Revised Codepen

    Note that although this code does what the question asks – it wraps flex items in their container before the container itself wraps – it's only meant to convey the basic concept of the solution. Issues like margin and width for flex items, which I considered beyond the scope of this question, may still need to be addressed.

    0 讨论(0)
提交回复
热议问题