A standard module definition for Sass

Since becoming a fan of Sass, one thing that has bothered me is that not much has been written about best practices for structuring Sass projects. This is one of a series of articles we will be writing to talk about some of the things that folks are doing to make their projects better.

In this article, I’d like to kickstart the discussion on developing a Standard Module Definition for Sass. I’ll start by sharing a couple of principles that I’ve found helpful for structuring Sass projects. (The principles here apply mostly to writing Sass for non-library code. We’ll talk more about some ideas for structuring library modules in a future article.)

1. A module is a unit of code contained in a partial

I like to define modules in Sass partials. Since Sass doesn’t currently have a way to namespace code, the easiest way to group code by function is to do so in a partial. One module per file. Example module names in typical projects might include: buttons, forms, lists, and typography.

2. Importing a module should never output code

I’m a strong believer in keeping your modules free of anything that would cause immediate CSS output. The idea is that you should be able to import any number of modules into your code-base and then make selective calls to control the output. This pretty much limits modules to mixins, functions, and variable definitions. (Sass 3.2 also introduces placeholder selectors which could also be used in a module definition.)

3. Each module should have a primary mixin

If appropriate, a primary mixin should be included in each module that outputs the standard usage of the module. This one is a little tricker to explain with words, so let me show you in code.

Here is an example _buttons.scss:

// Primary mixin
@mixin buttons {
  a.button, button {
    @include button(black, silver);
    &.blue  { @include button(white, blue); }
    &.red   { @include button(white, red); }
    &.green { @include button(white, green); }
  }
}

// Button mixin
@mixin button($text-color, $bg-color) {
  font: 12px bold sans-serif;
  padding: 3px 8px;
  @include color-button($text-color, $bg-color));
  &:hover, &:focus { @include color-button($text-color, lighten($bg-color, 10%)); }
  &:active { background: darken($bg-color, 5%); }
}

// Color button mixin
@mixin color-button($text-color, $bg-color) {
  color: $text-color;
  border: 1px solid mix(black, $bg-color);
  @include background-image(
    linear-gradient(
      lighten($bg-color, 5%),
      darken($bg-color, 5%)
    )
  );
}

...

The idea here is that the buttons module includes all kinds of mixins for creating and styling buttons, but the primary mixin demonstrates and applies the default usage of the appropriate mixins. This makes it super simple to use the default behavior for a module in a stylesheet.

Here’s an example of how I often combine modules in my main stylesheet:

.content {
  @include typography;
  @include buttons;
  @include lists;
  @include forms;
  ...
}

4. The name of the primary mixin should inherit the name of the module

I’d recommend that you try to pluralize your module names, where appropriate, and the name of your main mixin for that module should be the same as the name of the module itself. This simple naming convention will make it easy to import and use your modules without thinking hard about the names.

5. Variable definitions should always be defaulted

If a module defines top-level variables, they should always be defined with the !defaultdirective. This will make it much easier to override those variables in a theme stylesheet or when reusing the module for other purposes.

Here’s an example of using the !default directive to declare defaults for variables within a module:

$base-font-family: Helvetica, Arial, sans-serif !default;
$fixed-font-family: monospace !default;

6. Almost all project CSS should be written in modules

I like to code almost all of my CSS in modules using this pattern. This makes it much easier to reuse styles across stylesheets for a given project or even to share code between projects. It also helps me think about my code in a modular way from the very beginning – a discipline that I find quite helpful.

For me, modules have become the basic units or building blocks of my Sass projects. What practices do you find helpful for structuring your own projects?

Building a CSS framework with Sass

Over the past few years, the “CSS framework” topic has been one of the most hottest topics. There have been a number of permutations of CSS grid frameworks; fixed, fluid, elastic, responsive … you name it. To most seasoned front-end veterans, the topic of CSS frameworks isn’t new. But, let’s face it. Building a foundation of styles for each new project can be tedious and repetitive. But not with Sass.

Why do we use CSS Grid Frameworks?

Frameworks like Blueprint960 Grid SystemGrid Coordinates and Susy have created ways for designers to skip the repetitive, mundane and most importantly the math. With a CSS framework, front-end devs and designers can get a site laid out relatively quick with a minimal number of bugs, on top of a heavily tested code base.

Treesaver Boilerplate

At my day job I work with a company called Treesaver where we build magazine-style websites in HTML5 with an amazing bit of, “self-titled”, JavaScript called Treesaver. When I started with Treesaver a little over a year ago, that amazing bit of JavaScript and the ever transforming HTML5 spec was just about all we had to work with. All our HTML5 templates, JavaScript and CSS stylesheets were custom built from the ground up. In order to rapidly create the magazine-style websites we needed to develop, I immediately knew we needed to develop a custom CSS framework robust and flexible enough to support a wide array of grid layouts.

Sass, the perfect fit for creating CSS frameworks

I was introduced to Sass by my boss. Having access to variables, mixins, nested selectors and selector inheritance was quite literally impossible with vanilla CSS. Needless to say, I picked up Sass with a grin from ear to ear and just ran with it. The result? Seasons, a boilerplate for our self-titled JavaScript library Treesaver.

I immediately got into the variables and operations to calculate the grid. At the time I was tasked with designing and building about 5 publications, with slightly different grid measurements. I developed the core logic to determine all the math instead of pulling out the calculator for every calculation. Once I was done, all I had to do was swap out a class for the skin and voila. Magic! Everything updated to the new skin and grid layout.

Every new project brought new challenges

Of coarse our challenges didn’t stop there. Each new project added new challenges to the table. The core code was refined to a series of simple loops, image sizing was added and positioning was greatly improved. When adding a vertical grid, even the semantics of $column was brought into question and changed to $module-w based on Mark Boulton’s article, rethinking grids. The Sass looked nice and clean but the CSS output was starting to get hefty. Bloated CSS is a know problem with frameworks. They tend to just keep growing to satisfy every need, and making things more generalized and lean was a great ordeal. So I turned to Sass’s boolean features enable entire portions of the framework to be able to turn on and off. Sexy!

Before diving too deep into the code, Treesaver creates a number of unique challenges. All the HTML for layout exists in one file, resources.html. All the content is stripped from the <article>tags of pages. and placed into these “grids”. This manipulation of the DOM by the Treesaver JavaScript can be tough to figure our where some objects are placed. If that isn’t enough, the layouts are algorithmically chosen based on the amount and kind of content that can fit on each page. With all this complexity, the reasons for releasing a boilerplate were adding up.

All projects should start on a grid, but with grid layouts being defined in a separate file from the content grids need to be generated so the designer can do the taboo, layout in the HTML. That said, its just a matter of simple configurable loops to generate the output needed. These loops calculate for classes that position elements across the grid, So if I wanted an element to start on column 3 with a width of 4 columns it would be named <div class="c3 w4">. Maybe you want to turn the vertical grid on and position it 2 rows down? Add the class r2. It all sounds good so far but what if a project needs no less than a 30 column grid for some reason? Or a column width of 3px? These values may sound absurd but this framework is written in Sass so we have no excuse for locking down any values.

// GRID MEASURMENTS
@for $i from 1 through $columns // loop defines columns. c1, c2, c3 . . .
  .c#{$i}
    margin-left: grid($i) - $module-w
@for $i from 1 through $columns // loop defines widths. w1, w2, w3 . . .
  .w#{$i}
    width: grid($i)

// Vertical grid
$vertical-grid: false !default
$rows: 10 !default
@if $vertical-grid // Generate only if $vertical-grid is true. This code is usually not nessisary.
  @for $i from 1 through $rows // loop defines rows. r1, r2, r3 . . .
    .r#{$i}
      position: absolute
      top: (grid($i, $module-h) - $module-h) + $top
  @for $i from 1 through $rows // loop defines heights. h1, h2, h3 . . .
    .h#{$i}
      height: grid($i, $module-h)

Image resizing has been the trickiest part in creating Seasons. In order for Treesaver to calculate the layouts it needs to know the dimensions of each element, and while the dimensions of different sized images can be defined in the content, complex layouts would require about twelve different images to be defined in the content, something that was just getting too hard to manage. Now Sass is great at looping through and calculating ways to resize these images but can result in bloat just as easily. In fact, the earlier code was taking about 50k just to resize images! Pulling on nested mixins in the configuration containing the ratios used throughout the publication. Using a custom selector for ratio instead of a class targeting measurements for various page along with image ratios became smaller while supporting more use-cases.

@mixin ratios
  +ratio(16, 9)
  +ratio(4, 3)

// IMAGE + PAGE RATIOS
=ratio($width, $height, $cols: $columns)
  @for $i from 1 through $cols
    .r#{$width}x#{$height}.w#{$i},.container.w#{$i} [ratio="#{$width}x#{$height}"] img // Grid ratio, figure ratio.
      width: grid($i) // Width spans all columns
      height: round(grid($i) * ( $height / $width )) // Height is the proportion of the width.

+ratios // Run the code above. Ratios are defined in _config.sass

Creating powerful layout tools that don’t add heft to your file is another great point of creating a Sass framework. Creating tools for people to simply use the grid and control typography are just as if not more important for frameworks than just caring about the generated grids. Users should have as much control over aspects of layout from the stylesheets as they do with the classes the framework generated. For example grid is added as a function that generates different values based on the grid to use in stylesheets. Debug tools are another add-on that highlight elements. Ever made an element bright red just to see if it was showing up on the page at all? Well one-letter mixins rgbcm, and y will highlight elements in a verity of colors so you can quickly debug layouts. Also, throwing in some modular-scales, sprites, and CSS3 mixins for some fantastic layout possibilities. Want a list? you can find it here

Now configuring this monster may seem like a tall order, but it’s not that bad. Using the !defaultnot everything needs to be defined. In fact, out of the box Seasons is set up so it works, no need to change anything unless you want a value changed. The nature of frameworks is to be bloated, but the config allows you to trim out a number of features you may not wish to use. Not using fullbleed figures or inset captions, or want to write your own variation? Just turn them off in the config. Building styling frameworks in Sass is a whole new ballgame. The level of customization and flexibility needs to be far greater than that of CSS frameworks because this is how style frameworks should always work.

Making your CSS Dynamic with the Power of LESS

As a designer and theme expert for almost the past decade, I have seen many iterations of how our industry goes about creating a theme. The one constant for designers and theme developers is the use of CSS (Cascading Style Sheets). While yes there have been many versions and additions to CSS, it has remained relatively the same in the way we program it. My biggest complaint has always been the fact that CSS is a static language and contains no variables. This doesn’t sound like an issue until changes need to be made to the files afterwards.

Let me illustrate my point with an example. Instead of using #FF0000 to get a florescent red color, and use it hundreds of times in your style sheet, wouldn’t it be easier to store that color value inside a variable and just use that variable in all those places? That way if you want to recolor your webpage away from that florescent red to a less offensive color, you could just change the value of the variable in one place and that’s that.

Well my friends, Rejoice! LESS is here to make your CSS much more enjoyable.

Assumptions

It is good to note that some of the topics discussed below are meant for readers who have some basic Html and CSS knowledge as well as knowledge on coding structures. If your completely new I would highly recommend visiting http://www.w3schools.com/ to learn more about simpler techniques to get you started. That said …

What is LESS?

Less is a CSS pre-processor, meaning that it extends the CSS language, adding features that allow variables, mixins, functions and many other techniques that allow you to make CSS that is more maintainable, themable and extendable.

LESS is a superset of CSS. This means that all CSS code is valid LESS code but there are additional elements in LESS which would not be valid in CSS. This is great because your existing CSS is already valid LESS code, minimizing the learning curve to using LESS.

LESS adds much needed dynamic properties to CSS. It introduces variables, operations, function-like elements, even Javascript into the mix. It will make your life hassle free by enabling you to write stylesheets with a modular mindset.

Setting up and Using LESS

There are two ways to use LESS. You can create a LESS file and convert it on-demand using a Javascript file, or you can pre-compile it and use the resulting CSS file in your theme.

Option 1: Using The LESS Javascript File

The first option is very similar to adding jQuery to your site. First visit the LESS website and grab the Javascript file located in the download section. Once you have it, all you need to do is link it to your page like any other Javascript file.

1
<script src="js/less.js" type="text/javascript"></script>

Next, create a file with the .less extension and link it to your page with the code below:

1
<link rel="stylesheet/less" type="text/css" href="css/style.less">

Make sure that you link your LESS file before the Javascript file. Otherwise it will try to process the .less files before they are loaded.

Once you have this setup you can paste any previously existing CSS code into the LESS file or add an additional link to the CSS as LESS and CSS are compatible. While this method is the easiest for development I would recommend using the second method for your final production files.

Option 2: Compiling the LESS File to CSS

While this is a bit more tedious, in production scenarios this is preferred because the LESS processing will not be carried out by the users browser. LESS works by taking all the LESS code you write and converting it to CSS on the fly. Instead of having our site do this on demand we can convert our LESS file, save the CSS file output and use that instead of doing the on-demand conversion on each page load.

If your using a CMS like Drupal or WordPress you can find free modules that will allow you to compile these files for you directly on your web server instead of having your own machine compile these files.

If you’re developing a flat HTML site you can use Winless, a small local application which can detect all your LESS files automatically and whenever you save them it will convert them to a CSS file with the same name. This allows you to keep on linking to your CSS file on your pages while still utilizing the potential of LESS.

Start getting more with LESS

Finally, let’s start learning about writing LESS code. As you will see, if you understand CSS, LESS will be very easy to read and understand; it uses the same syntax style as CSS does, so it should all be familiar to you. Below

Variables the Key to LESS

This is by far the most basic and useful part of LESS. Variables in LESS work exactly like they do in Javascript and most other programming languages. You can use them to store a value and then use the variable name instead of the value itself whenever you need it.

1
2
3
4
5
6
7
8
@header-font: RageItalic;
h1, h2, h3, h4, h5, h6 {
    ;font-family: @header-font;
}
.large {
    ;font-family:@header-font;
}

In the example above we defined the @header-font variable and assigned the value “RageItalic” to it. We can now use this variable whenever we want to use the RageItalic font. If we decide we’d rather go with Helvetica as our heading font we don’t need to go through our whole file, we just change the value of the variable.

I find great use for variables when defining colors for a website. In the good old days (which weren’t that long ago) we used to do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
    Colors for our Website
    
    #ff0000 - Red – Links
    #cccccc - Light Gray - Borders
    #333333 – Dark Grey - Dark backgrounds and Heading colors
    #555555 - Mid Grey – Body Text Color
*/
body {
    background: #333333;
    color: #555555;
}
a {
    color:#ff9900;
}
h1, h2, h3, h4, h5, h6 {
    color: #333333;
}

There is nothing wrong with documenting your reused colors like this, it is good practice to help other designers using your stylesheets. The problem is that since it has nothing to do with the functionality of your stylesheet it has no other use than documentation itself.

With LESS we can modify our workflow and actually use our comments instead of it remaining as additional space in our file. This way if we want to make a change, it is 1 line replacement instead of finding a replacing multiple lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Colors for our Website */
@color-red: #ff0000;
@color-gray_light: #cccccc;
@color-gray_dark: #333333;
@color-gray_medium: #555555;
        
body {
    background: @color-gray_dark;
    color: @color-gray_medium;
}
a {
    color:@color-red;
}
h1, h2, h3, h4, h5, h6 {
    color: @color-gray_dark;
}

An important thing to note is variables in LESS act like constants. This means that they can only be defined once – as opposed to variables in other languages which can be defined as many times as you’d like. So it is good practice to define all your variables at the top of your less documentation.

Mathmatical Operations

Another fun addition with less is the ability to use mathematical operations. This allows us to achieve extremely granular and accurate control with the help LESS. As an example:

1
2
3
4
5
6
.button{
    @gridUnit: 5px;
    border:@gridUnit solid #ddd;
    padding: @gridUnit * 3;
    margin: @gridUnit * 2;
}

The above code defines the variable @gridUnit as 5px.  This variable is used in 3 segments of the code but we are multiplying the margin and padding to get consistant sizes.

Operations can be multiplication, division, addition and subtraction. Sometimes you will need complex functions. Order of operations applies to these math functions as in the example below. .box will have a width equal to 200px.

1
2
3
4
.box{
    @base_unit: 10px;
    width: @base_unit(20 + 20) – 2(@base_unit + 90)
}

Color Management

Some more useful features of LESS have to do with color management. You can use math operations to modify colors. If you want to change the value of a color you can actually do so by subtracting or adding another color to it. ….. Wait what? You heard me this means we can mix colors!

1
2
3
4
5
6
@color: #941f1f;
button {
    background: #941f1f + #222222;             
    border: #941f1f - #111111;
}

The above operation in the background will increase each HEX value by 2. This results in “B64141” which is a lighter variation of the original color. The operation in the border will decrease each HEX value by 1 resulting in a darker color: “830E0E”.

Class Nesting

When writing CSS you use a cascading style. Meaning we cascade classes in a line to specify the particular elements we want to style. To change the margin of paragraphs inside blog post teasers and article page only you could use the following code.

1
2
3
4
5
6
.article.teaser p{
    margin: 0 0 12px 0;
}
.article.post p{
    margin: 0 0 12px 0;
}

There is nothing wrong with this approach but when you also want to change the links, blockquotes, headings, pre-formatted text and so on inside this same element you would need to prefix each with “.article.teaser” and “.article.post”. This makes our code more tedious to write, larger, and harder to read.

In LESS we can nest these rules, which gives a shorter and more logical version of our stylesheet. Observe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.article{
    .teaser,
    .post {
        p{
            margin: 0 0 12px 0;
        }
        a {
            color: blue;
        }
        a:hover {
            color: green;
        }
        img {
            padding: 20px;
        }
    }
}

See what I did there? I nested an A, P, and IMG tag inside of two article classes. The tabbing is not necessary by the way but it makes it much more legible and easier to read. You can nest rules as much as you like which saves you a lot of worrying later on. Have you ever wanted to change the padding of something but were scarred because you didn’t know exactly what elements it might affect? By using nesting you can take a lot of the guesswork out of your CSS.

LESS Mixins

Mixins in LESS is not only a time saver but nothing short of organizational awesome! Have you ever created a rounded border on just the top two corners of all your elements? It is a terrible mess.

1
2
3
4
5
6
7
8
.tab {
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;     
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}

You end up with the code above on EVERYTHING! With LESS you can change all that by creating a mixin. Mixins are reusable elements which you can add as a style rule to any other element. The beauty of them is that there is no additional syntax to learn. You just call the class name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners {
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}
.tab {
    background: #333;
    color:#fff;
    .rounded_corners;
}
.submit {
    .rounded_corners;
}

In the above code we defined the .rounded_corners element to have rounded corners on top. When we add this to any other element as a mixin (see .tab) we are basically importing the rules we created for it. Due to the syntax of mixins you can use any previously defined element as a mixin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.rounded_corners { 
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;     
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px; 
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners;
}
.submit {
    .tab;     
    background: red;
}

The CSS rules for the .submit element will now call for rounded corners on top, a color of white and a background of red (the original #333 is overrided by red). Mixins can also take arguments, which are variables pass to the block of selectors when it is mixed in. These are known as parametric mixins.

Parametric Mixins

Parametric mixins sound extremely complex but they solve a problem in a very simple way. In the examples above you saw how we could define an element to have a 6px radius on its top corners. How about if we want an element to have a 3px radius? Should we declare new mixins for each new case? Of course not, we can achieve the same thing with parametric mixins.

These resemble functions because your’e not only create a mixin but you adding a variable which can be passed to it when you call it. Let’s rewrite the border radius example to take a look at how it’s done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners(@radius) { 
    -webkit-border-top-left-radius: @radius;
    -webkit-border-top-right-radius: @radius; 
    -moz-border-radius-topleft: @radius;
    -moz-border-radius-topright: @radius;
    border-top-left-radius: @radius;
    border-top-right-radius: @radius;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners(6px);
}
.submit {
    .rounded_corners(3px);
}

The above code will give our tab element a 6px radius while our submit element will receive a radius of 3px.

Adding Default Values to your Parametric Mixin

Along those same lines, sometimes 95% of your uses will involve only one size and you have an exception. In our case let’s say everthing we use the mixin a default value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners(@radius:6px) {    
    -webkit-border-top-left-radius: @radius;
    -webkit-border-top-right-radius: @radius; 
    -moz-border-radius-topleft: @radius;
    -moz-border-radius-topright: @radius;
    border-top-left-radius: @radius;
    border-top-right-radius: @radius;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners;
}
.submit {    
    .rounded_corners(3px);
}

In this example the tab element will receive the default 6px border radius but the submit element will receive the 3px one as needed.

Importing Files and Commenting in LESS

Thankfully, just like with normal CSS you can import files. This is great for organizing sections of styles. LESS lets you import both CSS and LESS files with the following syntax with the same call you would make from CSS:

1
2
3
@import "reset.min.css";
@import "framework.less";
@import "widgets";

It is important to note, while not necessary, you should include a .extension like .css or .less to help other users know what type of file it is looking for. If you do not include an extension LESS will assume it is a .less file. So in the example above 2 and 3 would be looking .less files and 1 would be trying to load a .css file.

As expected, multi-line comments are available in LESS in the same way that they are used in CSS. In addition LESS allows for single line comments to be used just like in PHP; by using a double forward slash.

1
2
3
4
5
6
7
8
/*
    This is my main LESS file.         
    It governs how most of the site looks.
*
body {
    padding:0px; // This resets the body padding
}

Wrapping Up

While we have only just scratched the surface of what LESS can do, these simple features will help anyone working in CSS to make it not only less time consuming but easier to modify through development and past production. For LESS beginners, remember that it is just like CSS so you can slowly learn the techniques above and integrate them one at a time into your style sheets.

For further information don’t forget to look at the less website and documentation located at http://lesscss.org. I hope you enjoyed this article and come back soon for more targeted in depth looks at LESS.

SASS vs LESS

“Which CSS preprocessor language should I choose?” is a hot topic lately. I’ve been asked in person several times and an online debate has been popping up every few days it seems. It’s nice that the conversation has largely turned from whether or not preprocessing is a good idea to which one language is best. Let’s do this thing.

Really short answer: Sass

Slightly longer answer: Sass is better on a whole bunch of different fronts, but if you are already happy in LESS, that’s cool, at least you are doing yourself a favor by preprocessing.

Much longer answer: Read on.

The Much Longer Answer

The Learning Curve with Ruby and Command Line and Whatever

The only learning curve is the syntax. You should use an app like CodeKitLiveReload, or Mixture to watch and compile your authored files. You need to know jack squat about Ruby or the Command Line or whatever else. Maybe you should, but you don’t have to, so it’s not a factor here. The fact that Sass is in Ruby and LESS is in JavaScript is of little consequence to most potential users.

Winner: Nobody

Helping with CSS3

With either language, you can write your own mixins to help with vendor prefixes. No winner there. But you know how you don’t go back and update the prefixes you use on all your projects? (You don’t.) You also won’t update your handcrafted mixins file. (Probably.)

In Sass, you can use Compass, and Compass will keep itself updated, and thus the prefix situation is handled for you. Bourbon is also good. There will be some back and forth on which of these project is “ahead.”

In LESS, there are also some mixin libraries battling to be the best. They are looking a lot better these days than they have in the past. Despite their marketing-y support charts, I don’t think they are quite as robust as the Sass versions. I’ve been led to understand in the past that the language of LESS itself doesn’t make it possible to build as robust of libraries on top of it. We’ll get to some of that next.

In both cases, the onus is on you to keep the preprocessor software itself up to date as well as these libraries. I also find that easier in Sass in general. For instance, Compass updates will just come automatically in CodeKit, or you use a Gem which is easy to update, while LESS mixins you’ll have to manually update a file yourself.

Winner: Narrowly Sass

Language Ability: Logic / Loops

LESS has an ability to do “guarded mixins.” These are mixins that only take affect whena certain condition is true. Perhaps you want to set a background color based on the current text color in a module. If the text color is “pretty light” you’ll probably want a dark background. If it’s “pretty dark” you’ll want a light background. So you have a single mixin broke into two parts with these guards that ensure that only one of them takes effect.

.set-bg-color (@text-color) when (lightness(@text-color) >= 50%) { 
  background: black;
}
.set-bg-color (@text-color) when (lightness(@text-color) < 50%) { 
  background: #ccc;
}

So then when you use it, you’ll get the correct background:

.box-1 {
  color: #BADA55;
  .set-bg-color(#BADA55);
}

That is overly simplified, but you likely get the idea. You can do some fancy stuff with it. LESS can also do self-referencing recursion where a mixin can call itself with an updated value creating a loop.

.loop (@index) when (@index > 0) {
  .myclass {
    z-index: @index;
  }
  // Call itself
  .loopingClass(@index - 1);
}
// Stop loop
.loopingClass (0) {}

// Outputs stuff
.loopingClass (10);

But thats where the logic/looping abilities of LESS end. Sass has actual logical and looping operators in the language. if/then/else statements, for loops, while loops, and each loops. No tricks, just proper programming. While guarded mixins are a pretty cool, natural concept, language robustness goes to Sass. This language robustness is what makes Compass possible.

For example, Compass has a mixin called background. It’s so robust, that you can pass just about whatever you want to that thing that it will output what you need. Images, gradients, and any combination of them comma-separated, and you’ll get what you need (vendor prefixes and all).

This succinct and intelligible code:

.bam {
  @include background(
    image-url("foo.png"),
    linear-gradient(top left, #333, #0c0),
    radial-gradient(#c00, #fff 100px)
  );
}

Turns into this monster (which is unfortunately what we need for it to work with as good of browser support as we can get):

.bam {
  background: url('/foo.png'), -webkit-gradient(linear, 0% 0%, 100% 100%, color-stop(0%, #333333), color-stop(100%, #00cc00)), -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 100, color-stop(0%, #cc0000), color-stop(100%, #ffffff));
  background: url('/foo.png'), -webkit-linear-gradient(top left, #333333, #00cc00), -webkit-radial-gradient(#cc0000, #ffffff 100px);
  background: url('/foo.png'), -moz-linear-gradient(top left, #333333, #00cc00), -moz-radial-gradient(#cc0000, #ffffff 100px);
  background: url('/foo.png'), -o-linear-gradient(top left, #333333, #00cc00), -o-radial-gradient(#cc0000, #ffffff 100px);
  background: url('/foo.png'), -ms-linear-gradient(top left, #333333, #00cc00), -ms-radial-gradient(#cc0000, #ffffff 100px);
  background: url('/foo.png'), linear-gradient(top left, #333333, #00cc00), radial-gradient(#cc0000, #ffffff 100px);
}

Winner: Sass

Website Niceitude

LESS has a nicer, more usable website. The Sass documentation isn’t awful. It’s complete and you can find what you need. But when competing for attention from front end people, LESS has the edge. I don’t doubt this plays a large role in LESS currently winning the popularity race.

I know that the Sass website is undergoing a major overhaul and lots of awesome people are working on it. It seems to me that it’s going very slowly though.

Winner: LESS

The @extend Concept

Say you declare a class which has a bit of styling. Then you want another class which you want to do just about the same thing, only a few additional things. In LESS you’d likely:

.module-b {
   .module-a(); /* Copies everything from .module-a down here */
   border: 1px solid red;
}

That’s an “include” essentially. A mixin, in both languages. You could use an include to do that Sass as well, but you’re better off using @extend. With @extend, the styles from .module-a aren’t just duplicated down in .mobule-b (what could be considered bloat), the selector for .module-a is altered to .module-a, .module-b in the compiled CSS (which is more efficient).

.module-a {
   /* A bunch of stuff */
}
.module-b {
   /* Some unique styling */
   @extend .module-a;
}

Compiles into

.module-a, .module-b {
  /* A bunch of stuff */
}
.module-b {
  /* Some unique styling */
}

See that? It rewrites selectors, which is way more efficient.

In LESS, every single class is also a mixin, programmatically muddies the waters, but is easier to understand at first.

As of LESS 1.4, it also supports extend. You can see some examples when we upgrade to it on CodePen. It’s a bit funky in that it doesn’t extend selectors nested in the original class unless you use an additional all keyword. Having the option to go either way seems like it’s actually more powerful to me, but also wary of what’s going on under the covers.

Sass also has the power to extend “placeholder” classes. Essentially invisible classes, in the format of %placeholder { }. This is useful for using internal naming that makes sense there but wouldn’t as actual class names.

Winner: Sass

Variable Handling

LESS uses @, Sass uses $. The dollar sign has no inherit meaning in CSS, while the @ sign does. It’s for things like declaring @keyframes or blocks of @media queries. You could chalk this one up to personal preference and not a big deal, but I think the edge here is for Sass which doesn’t confuse standing concepts.

Sass has some weirdness with scope in variables though. If you overwrite a “global” variable “locally”, the global variable takes on the local value. This just feels kind of weird.

$color: black;           
.scoped { 
  $color: white;
  color: $color;        
}                        
.unscoped {     
  // LESS = black (global)
  // Sass = white (overwritten by local)
  color: $color;          
}

I’ve heard it can be useful but it’s not intuitive, especially if you write JavaScript.

Winner: Tossup

Working with Media Queries

The way most of us started working with @media queries was adding blocks of them at the bottom of your main stylesheet. That works, but it leads to mental disconnect between the original styling and the responsive styles. Like:

.some-class {
   /* Default styling */
}

/* Hundreds of lines of CSS */

@media (max-width: 800px) {
  .some-class {
    /* Responsive styles */
  }
}

With Sass or LESS, we can bring those styles together through nesting.

.some-class {
  /* Default styling */
  @media (max-width: 800px) {
    /* Responsive styles */
  }
}

You can get even sexier with Sass. There is a really cool “respond-to” technique (see code by Chris EppsteinBen Schwarz, and Jeff Croft) for naming/using breakpoints.

=respond-to($name)

  @if $name == small-screen
    @media only screen and (min-width: 320px)
      @content

  @if $name == large-screen
    @media only screen and (min-width: 800px)
      @content

The you can use them succinctly and semantically:

.column
    width: 25%
    +respond-to(small-screen)
      width: 100%

Nested media queries are a fantastic way to work. Rumor has it Sass 3.3 will have more features to make this even more useful, including a way to make extend work within media queries which is currently impossible in both LESS and Sass.

Winner: Sass

Math

For the most part, the math is similar, but there are some weirdnesses with how units are handled. For instance, LESS will assume the first unit you use is what you want out, ignoring further units.

div {
   width: 100px + 2em; // == 102px (weird)
}

In Sass, you get a clear error: Incompatible units: ’em’ and ‘px’. I guess it’s debatable if it’s better to error or be wrong, but I’d personally rather have the error. Especially if you’re dealing with variables rather than straight units and it’s harder to track down.

Sass will also let you perform math on “unknown” units, making it a bit more futureproof should some new unit come along before they are able to update. LESS does not. There is some more weird differences like how Sass handles multiplying values that both have units, but it’s esoteric enough to not be worth mentioning.

Winner: Narrowly Sass

Active Development

I’m going to update these numbers since it’s been enough time since the original writing of this article.
05/16/12 01/12/13 06/25/13
Number of open issues on LESS 392 112 142
Number of open issues on Sass 84 83 110
Pending pull requests on LESS 86 10 5
Pending pull requests on Sass 3 7 11
Number of commits in the last month in LESS 11 84 2
Number of commits in the last month in Sass 35 14 14

None of that stuff is any definitive proof that one project is more active than the other, but it is interesting to look at stats. As I understand it, both of the leads work on the languages in whatever little free time they have, as they both have other major new projects they are working on.

LESS has been pretty actively lately, but now Sass has gotten much more active too, due to a core member getting to focus on it directly.

Winner: Tossup