Like it or not, if you’re a WordPress developer CSS is part of your life.
One of the reasons that CSS bothers me so much is that writing it involves a constant violation of the golden rule of programming: “don’t repeat yourself.” While I’m still not a designer, learning to use the CSS pre-processor SASS has allowed me to write CSS in a sane manner. Not only is SASS more efficient, but I think it leads to an overall better design.
The best part about SASS is that its an actual programming language, which means if you know the basics of how a programming language works—i.e. variables, arrays, and control structures—it’s easy to learn. That is once you understand its syntax.
In this article, I will be comparing SASS to the conventions of PHP, which are familiar to WordPress developers. Just like any new language, things will be a little different, but the foundation is the same. Most importantly, SASS allows us to establish and use patterns in our code without resorting to cut and paste.
Before We Begin
Before we start, there are two things to keep in mind: First, I’m assuming you have a basic familiarity with PHP form WordPress development. Second, it’s important to keep in mind that SASS has two different file extensions, .sass and .scss, each with its own syntax. In this article, I will be using the .scss syntax. No one uses .sass syntax, which is similar to PAML and HAML.
Also, SASS can’t be loaded by your browser. It has to be compiled into CSS. SASS compilers are outside the scope of this article, but it isn’t a big deal. You can easily use either a GUI tool like CodeKit, or a grunt task to compile it.
Finally, remember that valid CSS is valid SASS. Everything you know about CSS applies to SASS, no need to relearn properties, rules, and selectors.
Using Variables
One of the coolest things about SASS is variables. Variables act almost exactly like you’d expect them to from using them in PHP. The biggest difference between a variable in SASS and a variable in PHP, is that a SASS variable can only be a string. Don’t worry about that limitation as we’ll get past that in a bit. The other important difference is that variables are declared with a colon instead of an equals sign. Also, since variables can only contain strings, there is no need to add quotes around the value.
PHP:$black = '#1A0000';
SASS:$black = #1A0000;
A great use for variables is to store color values. In fact, this is the biggest reason why I believe SASS leads to better design—it allows you to treat colors as a pallette.
A good design generally involves only a handful of colors, plus various shades and tints. When writing traditional CSS, you end up with the same color values repeated all over the place, making it a burden to change them. When I use SASS, the first thing I generally do is define my colors, like this:
$primary: #608D4E; $secondary: #85794D; $highlight: #ABC147; $accent: #26ADA1; $background: #CED9BC;
Now I can change my color palette by modifying those few lines and the changes will be made to the rest of the design.
Mixins
Mixins are a directive that’s similar to PHP arrays and functions. They are essentially containers for groups of CSS declarations. Mixins allow you to create repeating patterns of CSS declarations and avoid writing repeating code.
In a simple mixin, you write a CSS declaration, but in place of the class or ID, you use @mixin NAME_OF_MIXIN. For example:
@mixin right-tilt-rounded-borders { -webkit-border-radius: 6px; -webkit-border-top-right-radius: 50px; -moz-border-radius: 6px; -moz-border-radius-topright: 50px; border-radius: 6px; border-top-right-radius: 50px; }
Now, instead of repeating these 6 lines over and over again, wherever you need this pattern, you simply use @include right-tilt-rounded-borders. For example:
.call-to-action-box { @include right-tilt-rounded-borders; }
Mixins can also operate like functions, since they can accept one or more parameters that are used in the mixin. For example, if we wanted to add a border with a variable width and color, we could add variables for each value to this mixin. It would now look like this:
@mixin right-tilt-rounded-borders( $color, $width ) { border: $width solid color; -webkit-border-radius: 6px; -webkit-border-top-right-radius: 50px; -moz-border-radius: 6px; -moz-border-radius-topright: 50px; border-radius: 6px; border-top-right-radius: 50px; }
. . .and we would use it like this:
.call-to-action-box{ @include right-tilt-rounded-borders( $primary, 1px ) ; }
Mixins can even contain other mixins. This means that we can define a mixin that is made of other mixins. To build a primary and accent color version of our borders mixin, we do this:
@mixin primary-tilt-right { @include right-tilt-rounded-borders( $primary, 1px ) ; } @mixin accent-tilt-right { @include right-tilt-rounded-borders( $accent, 1px ) ; }
Functions
In the previous section, I was careful not to totally equate mixins with functions, since SASS has functions as well. Since this article is geared towards getting you up to speed with using SASS and prebuilt SASS frameworks—not writing your own framework or library—I will not discuss building functions.
There are a great deal of built-in functions in SASS that you should be aware of. One of the most useful set is the color manipulation functions. Earlier, I talked about defining your color palette in variables. I didn’t show any tints or shades though, since I like to create those with functions.
To build off the color palette from the previous section, you can add tints and shades using the darken and lighten functions:
$primaryTint = lighten( $primary, 30% ); $primaryShade = darken( $primary, 30%); $accentTint = lighten( $accent, 30%); $accentShade = darken( $accent, 30% );
Now that seems like a lot of redundant code, but it’s okay because I’ve actually only rewritten it once, as we will discuss in the next section.
File Imports
SASS has the ability to include one file in another, similar to PHP’s include() and require(). In SASS, you use @import PATH/TO/FILE to include another file. These files that are included—which are called partials—can be used to organize your SASS into multiple partials, each named for their purpose. For example, you may have a partial called ‘typography’ and another called ‘forms.’
If you look at how a SASS library is structured, it generally has one file for setting up global variables and another for including components. For example, this settings partial in Foundation sets up the global functions while the main file includes that partial and all of the component-specific partials.
Partials tend to get used like classes in PHP—as containers for reusable code. For example, I have one partial for setting up all of my variations on my main colors including the tints, shades, and complements. I copy the same file into each of my projects and import it directly after defining the color palette.
Operators
Like other programming languages, SASS provides a basic mathematical operator. Want to set an element to have a width that is half of a defined variable, say $max-width? You can just divide $max-width by 2. For example, here is a simple grid system.
$row-width = 1200px; .row { max-width: 1200px; } .row .half { display:inline; float:left; width: $row-width/2; } .row quarter { display:inline; float:left; width: $row-width/4; }
And yes, I know that I can reduce the redundancy in that code using nesting, but we’re not there yet.
Control Structures
SASS also provides basic control structures, like if, if/else, each, for, and while, which work the same way as they do in PHP but with a different syntax.
If statements are great for use inside of a mixin definition. In this next example, we add a border color to the right-tilt-rounded-borders mixin from before, but use an if/else structure to change the color of the border based on its width.
@mixin right-tilt-variable-borders( $width ) { @if $width < 3 { border-color: $primary; } @else { border-color: $primaryTint; } border-width: $width; @include right-tilt-rounded-borders; }
In PHP, we would do something similar, like this:
function right-tilt-variable-borders( $width ) { if ( $width < 3 ) { echo 'border-color: '.$primary'; } else { echo ' border-color: $primaryTint;` } }
For loops in SASS work just like for loops in PHP, and are great for creating sequential named classes, or creating scaled sizes. For example, here we create a set of classes that increment font size by the golden ratio. Notice that the incremental variable, in this case $i, is used as #{$i}, which will output as the current count of the loop (1,2,3, or 4).
@for $i from 1 through 4 { .gText-#{$i} { font-size: .618em * $i; } }
‘@for $i from 1 through 4’ syntax that sets up the for loop, is the equivalent in PHP to ‘for ( $i = 0; $i <= 4; $i++ ).'
Along with for loops, foreach loops in PHP are two of the most common ways to avoid writing repetitive code. In SASS, what we call a foreach loop in PHP, is called an each loop. To process a comma-separated list of strings in SASS, we define the variable to loop through, and then we write a CSS declaration using the variable. We use the same #{$variable} formatting as in the for loop.
@each $city in Pittsburgh, London, Paris, Tokyo { .#{$city}-banner { background-image: url('/images/#{$city}.png'); } }
In PHP, the equivalent to ‘@each $city in Pittsburgh, London, Paris, Tokyo’ would be:
$cities = array( 'Pittsburgh', 'London', 'Paris', 'Tokyo' ); foreach ( $cities as $city )
In both our for and each loops examples, we were able to write one CSS declaration in place of four. Of course, since these control structures can be used for a practically infinite number of iterations, you can see how they are a key component to how SASS can free us from writing repetitive CSS.
Nesting
Control structures are very useful, and along with mixins they make it possible to easily create libraries of design patterns in your stylesheets. The capability of SASS that saves the most repetitive coding in your front-end work will be nesting.
One of the most annoying parts of CSS is declaring the font color of an element, along with different colors for links, active links, visited links, and what to do in each of these cases on hover requires different declarations. SASS changes by allowing us to nest these declarations.
Instead of this in CSS:
.menu { color: red; } .menu a { color: red; }
This is only a small part of what we would need, but writing all of that redundant code drives me nuts.
With SASS I can accomplish the same goal, like this:
menu{ color: #primary; a { color: $accent; &:hover {color: $accentShade;} } a:visited { color: $highlight; &:hover {color: $highlightShade;} } }
Notice the double nesting with the :hover pseudo-selector. For those we use “&” to represent the parent element. So &:hover, in this case, is equivalent to .menu a:hover.
Go Forth and Stay SASSy
I hope that this brief introduction has opened your eyes to the simplicity and power of SASS. Don’t forget, that the point of SASS is to make your life easier. Be sure to make use of the many SASS libraries that already exist, such as Foundation and Bourbon.
3 Comments