How you should be using Sass extends

Sass is an incredible preprocessor, and over the last year has revolutionized my work flow. One of the slickest features, in my opinion, is Sass’s ability to extend classes you’ve already authored. A quick example would be:

1
2
3
4
5
.first-class
	margin: 12px

.second-class
	@extend .first-class

What we have is ‘.second-class’ extending ‘.first-class’. The output would result in:

1
2
3
.first-class, second-class {
	margin: 12px;
}

As you can see, the ‘@extend’ function concatenates our styles for us.

What does this mean?

It means we have the ability to create helper partials that we can extend all over the place! These helper classes are similar to variables in the sense that we can extend them all over, but only need to change them in one place to update everywhere. An example:

1
2
3
4
5
6
7
8
9
10
11
12
13
// _placeholders.sass

%margin--auto
	margin: auto

%bg--white
	background-color: #fff

// _layout.sass

.header
	@extend %margin--auto
	@extend %bg--white

In the example above, we have a Sass partial named ‘_placeholders.sass’. This partial will hold all of our ‘invisible classes’. Invisible classes do not get output into your compiled CSS, they are just meant to extend within your Sass files.

By using extends, you can create placeholder classes for your box model, common colors, backgrounds, fonts, and a myriad of other presentational styles that are ready to be extended throughout your Sass.

What should go in my placeholder file?

There is no right and wrong answer here, by the rule of thumb for me is generally presentational classes. Mine will often look like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// _placeholders.sass

/////////////////////////////////////////
// text
/////////////////////////////////////////

%text--center
	text-align: center

%text--right
	text-align: right

%text--left
	text-align: left

/////////////////////////////////////////
// floats
/////////////////////////////////////////

%float--left
	float: left

%float--right
	float: right

%float--none
	float: none

/////////////////////////////////////////
// colors
/////////////////////////////////////////

%color--white
	color: #fff

%color--black
	color: #000

%color--grey
	color: $grey

// etc, etc

These classes will be available for me to extend throughout my layout and individual modules. My framework Cavern is based on these invisible classes, and uses them and Sass variables to control the output and weight of your final CSS file. Check it out if you’re interested in learning more about Sass and ‘@extends’!