@mixin and other CSS @at-rules in Sass/SCSS

You've probably seen CSS rules which start with the at-sign such as @font-face for custom fonts or @media used for responsive styling based on screen size. Maybe you've even used @keyframes for CSS animations. These so-called at-rules can go around normal CSS rules (normally a rule would simply be one or more selectors followed by lines of rules within curly braces).

But the @-rules are rarely sprinkled throughout a stylesheet.

In preprocessed CSS like Sass, many new at-rules are possible. Here we're using Sass/SCSS.

What's SCSS? It's Sassy CSS, and .scss is the new, preferred Sass file extension. Use .scss instead of .sass and the old grammar.

Sass brings with it many of its own @-rules of much more variety than normal CSS supports. Think of the Sass at-rules as new keywords (like the reserved words in a programming language). Basically, any new keyword which Sass adds is preceded by @, and other programming language-like features in Sass use prefix characters like $ for variables (also :, %, #, &).

Sass also includes at-rules which already existed in normal CSS but gives them a slightly different meaning. This includes @import and @media.

Other useful Sass at-rules are @extend, @include, @at-root, as well as "control" words useful in functions for adding logic: @if, @while, @each, etc.

But a really useful feature of Sass is the @mixin, and related at-rule @function. The two are similar, providing reusable shortcuts to cut down on repeating big chunks of code. But a mixin is a type of macro, perhaps familiar to C-language family users or even assembly language programmers. Macros are preprocessed and churn out code in the same language as the source. A function, on the other hand, is written in the programming language and executed. So they are processed at different levels and a macro is processed before a function or any other code.

Sass mixins are useful for simplifying many lines of vendor-specific rules (e.g. rules that start with -webkit- or -moz-, etc.) for new experimental CSS features into a single line. This line then expands into all the vendor rules because they are generally very similar lines with a single value. This value can be used by the mixin as an argument, much like a function.

There is about to be native support in CSS for mixins. However, the native mixins will not support using arguments and the syntax is different from Sass mixins. So it will still make sense to use Sass and preprocess into native CSS.

If, instead of repeating chunks of text, you want to calculate values, then use Sass @function instead of @mixin. A function can use any math expression that can otherwise be used in Sass, as well as having controls (like @if or @each) to take different paths using logic and looping.

Add new comment