SASS: Fundamentals of Operations
Theory: Mixins
An important tool in the SASS preprocessor's toolkit is mixins. These are repeating portions of code that we can include in various selectors. It sounds like template selectors, right? It's just like that in its basic form, but mixins have many more options.
First, let's deal with reusing styles. Let's create a simple style reset mixin.
To create a mixin, we specify the keyword @mixin and give it a unique name. Inside this mixin, we write down all the necessary rules:
To include a mixin in the selector, we use the @include keyword and then give the mixin's name we want to include. For example, let's reset the indents in the bulleted list:
After compiling, we get the following CSS code:
It's also possible to nest mixins into each other, which allows you to make a new mixin based on an existing one:
Note that inside the horizontal-menu mixin, we connected the two above mixins and then used it to style our menu. All styles from the flex-between and reset mixins will be inside the horizontal-menu mixin. The final CSS code will look like this:
The preprocessor runs sequentially, so the order in which we include the mixins may make a difference in some cases. Don't forget to keep an eye on it. Also, don't forget to supervise the nesting level of the mixins. Although SASS allows you to nest mixins within each other, I don't recommend going too deep. The more we nest mixins, the less control we have over the styles. The creators of mixins designed them primarily to make it easier to write repeating CSS code. If you feel like you're going too deep with nesting, stop, breathe, and think. Maybe you find that it is better to use some styles without mixins.
Often, developers use mixins for properties that need support in older browsers and specify vendor prefixes for these properties. If we use the box-shadow property and need support for older browsers like Firefox 3.5, Chrome 9, and Safari 4.3, we should use the vendor prefixes -moz- and -webkit-. This is the kind of code we can use mixins for: