skip to Main Content

I have CSS Grid which has 7 columns and multiple rows. Is it possible to have first 4 columns occupying same width as last 3 columns when column width is dynamic?

In example below, I explicitly set grid-template-columns to specific widths to reproduce final result I want, but in real case scenario, I need to have dynamic width columns and grid, but first 4 columns should always be equal width to other 3 columns.

.grid {
  display: grid;
  width: 720px;
  grid-template-columns: repeat(4, 3fr) repeat(3, 4fr);
  >div {
    border: 1px solid gray;
  }
  .expl1 {
    grid-column: 1/span 4;
  }
  .expl2 {
    grid-column: 5/-1;
  }
}
<div class="grid">
  <div>Col 1</div>
  <div>Col 2</div>
  <div>Col 3</div>
  <div>Col 4</div>
  <div>Col 5</div>
  <div>Col </div>
  <div>Col 7</div>
  <div class="expl1">Above width is 4 * 90px = 360px</div>
  <div class="expl2">Above width is 3 * 120px = 360px</div>
</div>

Is there any solution without splitting grid into two columns and putting subgrid of 4 columns into first column and subgrid of 3 columns into second column?

2

Answers


  1. Sure but don’t use repeat

    .grid {
      display: grid;
      width: 720px;
      grid-template-columns: 3fr 3fr 3fr 3fr 4fr 4fr 4fr;
      >div {
        border: 1px solid gray;
        grid-column-end: span 1;
      }
      .expl1 {
        grid-column: 1 / span 4;
      }
      .expl2 {
        grid-column: 5/-1;
      }
    }
    <div class="grid">
      <div>Col 1</div>
      <div>Col 2</div>
      <div>Col 3</div>
      <div>Col 4</div>
      <div>Col 5</div>
      <div>Col </div>
      <div>Col 7</div>
      <div class="expl1">Above width is 4 * 90px = 360px</div>
      <div class="expl2">Above width is 3 * 120px = 360px</div>
    </div>
    Login or Signup to reply.
  2. Yes, you can achieve this without splitting the grid into two columns or using subgrids. The key is to use fractional units (fr) in the grid-template-columns property while ensuring that the sum of the fractions for the first four columns is equal to the sum of the fractions for the last three columns.

    .grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr) repeat(3, 4/3fr);
    }
    
    .grid > div {
      border: 1px solid gray;
    }
    
    .expl1 {
      grid-column: 1 / span 4;
    }
    
    .expl2 {
      grid-column: 5 / -1;
    }
    <div class="grid">
      <div>Col 1</div>
      <div>Col 2</div>
      <div>Col 3</div>
      <div>Col 4</div>
      <div>Col 5</div>
      <div>Col 6</div>
      <div>Col 7</div>
      <div class="expl1">Above width is 4 * 1fr</div>
      <div class="expl2">Above width is 3 * 4/3fr</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search