Julian Jelfs’ Blog

LESS (or SASS) can be MORE

Posted in Uncategorized by julianjelfs on April 27, 2013

When converting a conventional CSS file to SASS the other day it occurred to me that it could actually encourage less efficient CSS by creating the illusion of reuse. This seems specifically to be true when using mixins. Suppose I have several different kinds of icon and they just differ by background image, then I would naturally consider using a mixin to accomplish that like this:

@mixin icon($img) {
    background-image: url("#{$img}");
    background-repeat:no-repeat;
    background-position:center center;
    height:20px;
}

.error-icon
{
    @include icon("/images/error.png");
}

.save-icon
{
    @include icon("/images/save.png");
}

This gives me the illusion that I have reused that section of CSS. But really when you look at the output CSS you can see that the content of the mixin is duplicated:

.error-icon
{
    background-image: url("/images/error.png");
    background-repeat:no-repeat;
    background-position:center center;
    height:20px;
}

.save-icon
{
    background-image: url("/images/save.png");
    background-repeat:no-repeat;
    background-position:center center;
    height:20px;
}

In fact it is more efficient to create a separate CSS class for the common attributes and one for the icon specific background image like this:

.icon 
{
    background-repeat:no-repeat;
    background-position:center center;
    height:20px;
}

.error-icon
{
    background-image: url("/images/error.png");
}

.save-icon
{
    background-image: url("/images/save.png");
}

The moral of the story is not to forget that the important thing is is what actually gets generated, not just how cool your pre-processed file looks.

Tagged with: , ,