skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. What you have to do is change @container to @media, the rest of the code is fine.

        .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;
          }
          
          @media (max-width:500px) {
            .list {
              grid-template-columns: 1fr 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search