Search code examples
cssflexboxcss-grid

CSS Grid Dynamically assign grid column or grid-template-columns


I need to be able to dynamically assign the numbers of columns an item would take up in a grid row.

In flex I could just do something like give it a name like .col-sm-25 (imaginative, I know) and give it a styling of flex-basis: 25%. However, flex doesn't have the grid-gap property so I'm trying to see if there's a way to do this in css grid.

As it's dynamically created by the editor in our CMS system and they can't choose the container to add items into, grid-template-columns can only really be repeat(12, 1fr) or something to that effect.

Is there a way I can say for item .col-sm-25 to take up the next 4 available column in the grid row? I don't know what order the items will come in so can't say what grid-column-start would be.

I know it can be done in flebox but it just feels so hacky


Solution

  • Is there a way I can say for item .col-sm-25 to take up the next 4 available column in the grid row?

    Yes.

    Just define the grid-column-end as span 4

    Grid-column-end @ MDN

    span n

    Contributes a grid span to the grid item’s placement such that the column end edge of the grid item’s grid area is n lines from the start edge.

    .grid {
      display: grid;
      grid-template-columns: repeat(12, 1fr);
    }
    
    .box {
      border: 1px solid green;
      height: 50px;
    }
    
    .span-2 {
      grid-column-end: span 2;
      background: green;
    }
    
    .span-3 {
      grid-column-end: span 3;
      background: lightblue;
    }
    
    .span-4 {
      grid-column-end: span 4;
      background: lightgreen;
    }
    <div class="grid">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box span-4"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box span-4"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box span-2"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box span-3"></div>
      <div class="box"></div>
      <div class="box span-4"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>

    Note, as is shown this can lead to "breakage" of the grid where there are less than 4 columns left in the row.

    However, css-grid can back-fill using grid-auto-flow:dense;