csscontainer-queries

Use multiple conditions for CSS container queries


Important - this code only works on browsers with container queries enabled

How can I use multiple conditions at the same time for container queries? Using the syntax for @media queries doesn't seem to work.

In this example, the background changes to yellow based on the width and height of the element (resize it to see). But combining the conditions to make the background blue doesn't work.

.tile {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  resize: both;
  overflow: auto;
  container-type: size;
  container-name: tile;
}

.tile__inner {
  width: 100%;
  height: 100%;
}

@container tile (min-width: 100px) {
  @container tile (min-height: 100px) {
    .tile__inner {
      background: yellow;
    }
  }
}

@container tile (min-width: 100px) and (min-height: 100px) {
  .tile__inner {
    background: blue !important;
  }
}
<div class="tile">
  <div class="tile__inner"></div>
</div>


Solution

  • The combined syntax is correct in your example, and works as expected in Chrome v105 as well as Safari Technology Preview v152. I'm seeing the blue background applied when both width and height are 100px or larger.

    I would guess that you are using Safari TP v151 or earlier? There was a bug in Safari TP before v152 that required parenthesis around any combination/negation syntax. I expect this will work for you either by using parenthesis (which is also valid syntax):

    
    @container tile ((min-width: 100px) and (min-height: 100px)) {
      .tile__inner {
        background: blue !important;
      }
    }
    

    Or by upgrading Safari to the latest TP.

    codepen: https://codepen.io/miriamsuzanne/pen/dyeYoBr/30d17f519afe57c5d88f2c281dcbb5e2

    screenshot of a blue square on white background, with bottom-right handle for resizing