DEV Community

Cover image for CSS container queries with SASS mixins
Kevin J. Estevez
Kevin J. Estevez

Posted on

CSS container queries with SASS mixins

Have you ever wanted to apply certain styles based on the container width instead of the viewport width? well now you can do it using CSS container queries

That's pretty cool but as we used to do with media queries we might want to set standards for the codebase and define common breakpoints' variables to be used across the project.

  • Mobile devices – 320px — 480px.
  • iPads, Tablets – 481px — 768px.
  • Small screens, laptops – 769px — 1024px.
  • Desktops, large screens – 1025px — 1200px.
  • Extra large screens, TV – 1201px, and more.

If you're using some css pre-processor like SASS, then we will do something like a mixin to wrap the code:

For Media Queries

$breakpoint-xs: 480px;
$breakpoint-s: 768px;
$breakpoint-md: 1024px;
$breakpoint-l: 1200px;
$breakpoint-xl: 1900px;

@mixin x-small {
  @media screen and (min-width: $breakpoint-xs) {
    @content;
  }
}

@mixin small {
  @media screen and (min-width: $breakpoint-s) {
    @content;
  }
}

@mixin medium {
  @media screen and (min-width: $breakpoint-md) {
    @content;
  }
}

@mixin large {
  @media screen and (min-width: $breakpoint-l) {
    @content;
  }
}

@mixin x-large {
  @media screen and (min-width: $breakpoint-xl) {
    @content;
  }
}
Enter fullscreen mode Exit fullscreen mode

For Container Queries

If we try to do exactly the same for container queries, it won't work out, we need to make a slight change (scaping the variables values)

...
@mixin x-small {
  @container (min-width: $breakpoint-xs) { /* this will not work and you will see no error */
    @content;
  }
}

...
Enter fullscreen mode Exit fullscreen mode

So to make it work for container queries we need to scape the variables with the breakpoints like this: #{$breakpoint-xs}

...
@mixin x-small {
  @container (min-width: #{$breakpoint-xs}) { /* this will work but you will see the vs-code complaining about some syntax error, so just ignore it */
    @content;
  }
}
...
Enter fullscreen mode Exit fullscreen mode

The solution above is reported as an error (scss-(css-ruleorselectorexpected)) by VSCode, but when it compiles and runs just fine.

Thanks a lot to the solution I found in this thread by Michel Reij

Hope this could be helpful to someone else!
Thanks for reading.

Top comments (0)