htmlcsscss-gridcontainer-queries

@container queries don't change grid-template-columns value


Having a page where we require that if container width is below view size then change 5 columns into 2 columns and trying below:

.list {
  background-color: grey;
  display: grid;
  grid-gap: 4px;
  grid-template-columns: repeat(5, 1fr);
  container-type: inline-size;
}

.letter {
  display: grid;
  grid-auto-flow: row;
  justify-items: center;
  align-content: center;
  color: white;
}

@container (max-width:500px) {
  .list {
    grid-template-columns: repeat(2, 1fr);
  }
  .letter {
    background-color: green;
  }
}
<div class="list">
  <div class="letter">A</div>
  <div class="letter">B</div>
  <div class="letter">C</div>
  <div class="letter">D</div>
  <div class="letter">E</div>
</div>

But it doesn't work; checked in Chrome and Firefox in Ubuntu.


Solution

  • I think you are one container 'out'.

    This snippet introduces a wrapper which is set to be a 'container' so the .list element has a container to be tested.

    .wrapper {
      container-type: inline-size;
    }
    
    .list {
      background-color: grey;
      display: grid;
      grid-gap: 4px;
      grid-template-columns: repeat(5, 1fr);
    }
    
    .letter {
      display: grid;
      grid-auto-flow: row;
      justify-items: center;
      align-content: center;
      color: white;
    }
    
    @container (max-width:500px) {
      .list {
        grid-template-columns: repeat(2, 1fr);
      }
      .letter {
        background-color: green;
      }
    }
    <div class="wrapper">
      <div class="list">
        <div class="letter">A</div>
        <div class="letter">B</div>
        <div class="letter">C</div>
        <div class="letter">D</div>
        <div class="letter">E</div>
      </div>
    </div>