sass variable not working in container query

2.6k Views Asked by At

SCSS variables don't seem to work when used in a container query. For example this code works just fine:

.parent {
  container-type: inline-size;
  background: yellow;
}

@container (max-width: 800px) {
  .child {
      background:green;
  }
}

See pen: https://codepen.io/pwkip/pen/jOprKya

But when I try to use a sass-variable to define the breakpoint, it fails.

$width: 800px;

.parent {
  container-type: inline-size;
  background: yellow;
}

@container (max-width: $width) {
  .child {
      background:green;
  }
}

See pen: https://codepen.io/pwkip/pen/BaPzVZW

What's the problem here? Any workaround?

2

There are 2 best solutions below

0
On BEST ANSWER

I cannot find the definitive sass lang entry, but hash and curly brace is often used in @media queries.

@container (max-width: #{$width}) {
  .child {
      background:green;
  }
}

In Brave it works in that codepen; and so do the following:

@container (max-width: ${width} ) {
1
On

As "A Boston" already pointed out the issue seems to be that you don't use the hash syntax like in his first example.

I use https://www.sassmeister.com/ quite often to check what it compiles to.

In your Codepen you forgot to add a semicolon after

$width: 800px;
             ^

According to: https://developer.mozilla.org/en-US/docs/Web/CSS/@container @container queries are not supported for Firefox yet. Only Firefox Nightly supports it.

I've tested it in Chrome and it worked with the tweaks. Make sure your browser version is supported. My current Safari version did not work either (due to the version mismatch).