Search code examples
csscss-grid

Make grid-template-columns dynamic


I have a table whose some columns are created depends on data. I want to put those columns of fixed size between two specific columns.

And I'm implementing this like:

.grid {
  width: 290px;
  overflow-x: auto;

  display: grid;
  grid-template-columns: [index] 80px repeat(auto-fit, minmax(161px, auto)) [price] 210px
}

.col {
  grid-row: 1;
}

.col.index {
  grid-area: index;
  grid-row: 1;
}

.col.price {
  grid-area: price;
  grid-row: 1;
}
<div class='grid'>
 <div class='col index'>No</div>
 <div class='col'>Color</div>
 <div class='col'>Size</div>
 <div class='col price'>Price</div>
 <div>1</div>
 <div>Red</div>
 <div>Large</div>
 <div>1,000</div>
</div>

The first dynamic column Color is 161px-width which is what I wanted, but the second one Size is not 161px-width which I want it to be.

Is it possible to make it by static css? Or should I use inline-style?


Solution

  • Specify this at the gird items level not the container level

    .grid {
      width: 290px;
      overflow-x: auto;
    
      display: grid;
    }
    .grid :not(.col) {
      grid-row: 2;
    }
    .col {
      width: 161px;
      border: 1px solid red;
    }
    .col.index {
      width: 80px;
      border: 1px solid blue;
    }
    .col.price {
      width: 210px;
      border: 1px solid green;
    }
    <div class='grid'>
     <div class='col index'>No</div>
     <div class='col'>Color</div>
     <div class='col'>Size</div>
     <div class='col price'>Price</div>
     <div>1</div>
     <div>Red</div>
     <div>Large</div>
     <div>1,000</div>
    </div>