Change the number of columns and rows in a grid as the number of items increase

后端 未结 1 1253
陌清茗
陌清茗 2021-01-24 22:10

I have to design a responsive grid.
The grid should change based on the number of items (instead of the size of the screen).

From 5 to 6 items should be 2x3,
fro

1条回答
  •  孤独总比滥情好
    2021-01-24 22:19

    Implicit columns creation can do this. You can consider nth-child()/nth-last-child() to create a new column when you reach a specific number of columns:

    .container {
      display:inline-grid;
      grid-auto-columns:1fr;
      width:100px;
      vertical-align:top;
    }
    .container > :nth-child(2) {
      grid-column:2;
    }
    
    .container > :nth-last-child(5) ~ :nth-child(3),
    .container > :nth-last-child(7) ~ :nth-child(3), /* 7 = 5 + 2 */
    .container > :nth-last-child(9) ~ :nth-child(3){ /* 9 = 7 + 2 */
     grid-column:3;
    }
    
    .container > :nth-last-child(10) ~ :nth-child(4),
    .container > :nth-last-child(13) ~ :nth-child(4), /* 13 = 10 + 3 */
    .container > :nth-last-child(16) ~ :nth-child(4){ /* 16 = 13 + 3 */
     grid-column:4;
    }
    
    .container > :nth-last-child(17) ~ :nth-child(5),
    .container > :nth-last-child(21) ~ :nth-child(5), /* 21 = 17 + 4 */
    .container > :nth-last-child(25) ~ :nth-child(5){ /* 25 = 21 + 4 */
     grid-column:5;
    }
    
    .container > * {
      border:1px solid red;
    }
    .container > *::before {
      content:"";
      display:inline-block;
      padding-top:100%;
    }

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