on parameterized Sass mixins
¶ by Rob FrieselWhen I wrote 10 things I love about Sass, I included mixins on that list; and though I mentioned that they can be written to take arguments, I did not fully explore that. Combined with Sass’ functions and directives, parameterized mixins can really cut down on the repetitive CSS you need to write–especially when it comes to those -vender-specific
extensions.
By way of example, suppose you want to add a gradient background to some element. The CSS might look something like this:
.my-class { | |
/* fallback for browsers that do not support CSS3 */ | |
background: #222; | |
/* -moz requires "px" or % after the stop # */ | |
background: -moz-linear-gradient(top, #666, #222 32px); | |
/* -webkit does not require "px" after the stop $ */ | |
background: -webkit-gradient(linear, 0 0, 0 32, from(#666), to(#222)); | |
} |
In other words, at least three definitions for every gradient that you want to add. Now, you could do the same thing much more conveniently using Sass:
@mixin basic-linear-grader($base_color, $accent_color, $stop) { | |
// -moz gets the same $stop | |
$_moz_stop: $stop; | |
@if unitless($stop) { | |
// but we tack on the "px" if it's missing | |
$_moz_stop: #{$stop}px; | |
} | |
background: $base_color; | |
background: -moz-linear-gradient(top, $accent_color, $base_color $_moz_stop); | |
background: -webkit-gradient(linear, 0 0, 0 $stop, from($accent_color), to($base_color)); | |
} | |
.my-class { | |
@include basic-linear-grader(#000, #666, 32); | |
} |
A little extra work up-front, but it pays dividends: your gradient style becomes a one-liner everywhere else you want to define/use it; you only need to update it in one place if you fudged the syntax or want to make some other tweak. Plus, this is a pretty simple and straightforward example–the mixin itself could be further refined to take advantage of Sass’ variable defaulting system and other functions/directives to create an even more powerful/flexible mixin for your Sass arsenal.
Leave a Reply