Forward Advance Learning

Mixins, Includes & Functions

Mixins allow us to share common functionality around the place. We can write a single mixin, then include it in multiple places.

Here is a clearfix mixin. It adds code to tell a block to clear its contained floats:

@mixin clearfix {
&:after {
content:'';
clear:both;
display:table;
}
}

We can include it wherever we like:

.my_container {
@include clearfix;
}

Parameterised Mixins

Mixins can receive parameters, like so:

@mixin cols(num) {
width: $desktop / 12 * num
}

then:

article {
@include cols(6);
}

Exercise - Mixins

Create a button mixin which sets a width, a height, a background-color, a padding and display:inline-block. Apply it to the following:

  • <input type="submit">Click Me!</input>
  • <button>Click me!</button>
  • <a class="button">Click Me!</a>

Imports

We can split our code across more than one file, then import it. The output file will have access to all the imports.

Import filenames by convention start with an underscore, like so: _my_mixin.scss.

Import this with the @import statement like so:

@import 'variables/colours';

We use this to split out common sections of functionality.

Exercise - Imports

Extract your button mixin into a separate file, then import it. You may wish to create a folder called imports to contain your imports.

Break out the code for the header, sidebar and footer. Break out your variable declarations into sensibly named files (_colours.scss, _typography.scss, etc.) I expect the app.scss file to contain only imports.

Functions

A function is like a mixin, except it returns a variable rather than a set of CSS rules.

SASS comes with a set of built in functions transform variables, like so:

$red: #f00;
a {
color:darken($red, 30%);
}
a:hover {
color:lighten($red, 30%);
}

We can define our own functions, as with mixins:

@mixin col_width(num) {
@return $desktop / 12 * num
}

then:

article {
width col_width(6);
}

Exercise - Functions

  • Make use of the lighten function to create a harmonious colour scheme.
  • Use lighten($grey, 10%) to create a gradient background for your page.

Further Exercise - Libraries

Because SASS lets you create functions, there are various user created libraries you can make use of. Here we will use mathsass to give us trigonometry.

Grab Mathsass from here https://github.com/terkel/mathsass. @import it.

Now try to put some text on a sin curve.