Can I make a CSS grid with dynamic number of rows or columns?

前端 未结 5 2077
猫巷女王i
猫巷女王i 2020-12-13 08:51

What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let\'s assume there will always be four cells per row. Can I specify a grid

5条回答
  •  眼角桃花
    2020-12-13 09:18

    Okay, after reading the MDN reference, I found the answer! The key to dynamic rows (or columns) is the repeat property.

    const COLORS = [
      '#FE9',
      '#9AF',
      '#F9A',
      "#AFA",
      "#FA7"
    ];
    
    function addItem(container, template) {
      let color = COLORS[_.random(COLORS.length - 1)];
      let num = _.random(10000);
      
      container.append(Mustache.render(template, { color, num }));
    }
    
    $(() => {
      const tmpl = $('#item_template').html()
      const container = $('#app');
      
      for(let i=0; i<5; i++) { addItem(container, tmpl); }
      
      $('#add_el').click(() => {
        addItem(container, tmpl);
      })
      
      container.on('click', '.del_el', (e) => {
        $(e.target).closest('.item').remove();
      });
    });
    .container {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-template-rows: repeat(auto-fill, 120px);
      grid-row-gap: .5em;
      grid-column-gap: 1em;
    }
    
    .container .item {
    }
    
    
    
    

    P.S. Or you can use grid-auto-rows in my particular example.

提交回复
热议问题