This article first appeared on SitePoint in 2015 and republished on 14th June 2017 following a number of small corrections and revisions.
For me finding Sass was a revelation. For the longest time I had tired of writing plain or 'vanilla' CSS. For a small site it was fine, but for larger sites the CSS quickly got out of hand. Debugging was a nightmare and I couldn't help but feel like I could do more with my CSS.
I found Sass and everything changed. With Sass I could break my CSS down into modular chunks to make troubleshooting a breeze. I could also use programming concepts, such as functions and variables, when creating my CSS. And most importantly Sass introduced me to Mixins.
What Is a Sass Mixin?
A mixin allows you to create reusable chunks of CSS. Being able to do this will help you to avoid writing repetitive code. For example:
[code language="css"]
a:link { color: white; }
a:visited { color: blue; }
a:hover { color: green; }
a:active { color: red; }
[/code]
Writing this code over and over again can get old very quickly, especially if you have a large site with a lot of links. You can create the styles for your links with a Sass mixin like this:
[code language="sass"]
@mixin linx ($link, $visit, $hover, $active) {
a {
color: $link;
&:visited {
color: $visit;
}
&:hover {
color: $hover;
}
&:active {
color: $active;
}
}
}
[/code]
How to Include a Sass Mixin
To make use of a mixin you have to include it in your Sass files. To call the linx mixin from above you would add this line:
[code language="sass"]
@include linx(white, blue, green, red);
[/code]
The @include
directive allows you to use mixins within your Sass files.
How to Create a Sass Mixin
To create a mixin you use the @mixin
directive. For example:
[code language="sass"]
@mixin sample {
font-size: 12px;
}
[/code]
You define this directive by using @mixin
followed by the name of the mixin. You can also optionally include arguments in your mixin, like you did with the linx mixin above.
You can also use variables in your mixin, which are defined elsewhere in your Sass files. Let's say you wanted to use $font-base
as a variable in your mixin. As long as the variable has been defined you can use it in your mixin:
[code language="sass"]
$font-base: 12px;
@mixin sample {
font-size: $font-base;
}
p {
@include sample;
}
[/code]
The resulting CSS is:
[code language="css"]
p {
font-size: 12px;
}
[/code]
Arguments in Sass Mixins
Continue reading %Sass Basics: The Sass Mixin Directive%
by Reggie Dawson via SitePoint
No comments:
Post a Comment