Extend and Placeholders in Sass

There has been a lot of chatter recently around the @extend function in Sass. When used in combination with a placeholder class, the function is quite powerful and a great way to make your Sass more manageable. Unlike a variable that only defines one value for one property, @extend allows you to define a series of rules and properties that a group of elements could share. The most common example of this is with the clearfix hack for float layouts.

.clearfix:after { height: 0; content: "."; display: block; clear: both; visibility: hidden; }
.clearfix   { display: inline-block; zoom: 1; }

becomes

%clearfixAfter     { height: 0; content: "."; display: block; clear: both; visibility: hidden; }
%clearfix   { display: inline-block; zoom: 1; }

.clearfix:after { @extend %clearfixAfter; }
.clearfix   { @extend %clearfix; }

Say you have an element somewhere on your site that you don’t have access to, in a third party plugin or something, and you can’t add the clearfix class to it. With @extend, simply add the classes to your CSS and drop in the @extend just like above.

The Rub

The bad thing about @extend? Well, it doesn’t work in media queries. In the world of responsive web design this can be a deal breaker, but think of it this way. Placeholder classes and extend should be used when you’re defining margins, grids, basic button styles, etc. Not being able to use them inside media queries should be a non-issue for the most part.

A Work Around

If you’re stubborn like me though, and want a way that works everywhere, why not define a mixin and include it that way? When I want to include an icon font on my site, I use one mixin that prints out all the common properties I need:

@mixin icoFont(){
    font-family: 'icomoon';
    font-style: normal;
    speak: none;
    font-weight: normal;
    -webkit-font-smoothing: antialiased;
}

Say I want to add an icon font to an element’s :after pseudo class, like below:

p:last-child:after  { margin-left: 5px; width: 10px; height: 10px; content: '\35'; @include icoFont(); }

If this rule was in a media query it would still work!

So what do you think? What do you use @extend for? Do you always use placeholder classes?

posted in: Front End Development
tagged: , , , ,

Comments are closed