Mixins
A mixin is a piece of customizable and reusable code anywhere in your SASS file. Like a function, a mixin can take parameters.
// Elle se définit grâce à la directive @mixin puis le nom que vous souhaitez lui attribuer
@mixin inline-block {
// code
}
// Pour inclure votre mixins, une ligne suffit
@include inline-block;
Mixin with parameters
Thanks to mixins, you will be able to generate several dozen lines of CSS with a single (configurable or not) line in SCSS !
Example :
@mixin inline-block($align, $margin : 10px) { // Si aucune valeur n'est précisée alors $margin vaut 10px
display: inline-block;
vertical-align: $align;
margin-left: $margin;
}
// Appel de la mixin
.bloc {
@include inline-block(middle);
}
Compiled CSS file:
.bloc {
display: inline-block;
vertical-align: middle;
margin-left: 10px;
}
SASS does not integrate any predefined mixin. However, this is one of the strengths of Compass, which offers a hundred mixins ready to use: Compass Mixins.
Functions
The difference between a mixin and a function is the result returned once compiled. A mixin can generate several lines of CSS code while a function will only return a value.
Thanks to functions, you will be able to calculate the percentage of a block, convert a “px” unit to “em/rem,” or even lighten a color.
// Une fonction se définit avec la directive @function :
@function percentage($num) {
// code
}
// L'appel d'une fonction est différent des mixins.
// En effet, son utilisation se fera directement au niveau de la valeur d'un attribut
.bloc {
width: percentage($num/$container-width); // calcul le pourcentage de .bloc
color: darken(white, 20%); // assombrit la couleur de 20%
Find the complete list of SASS and Compass functions.