The Mighty Mixin
Mixins are similar to variables, in that you call them in much the same way. There are three differences between mixins and variables:
They start with a dot (.) instead of an @ symbol.
Instead of a general variable that you can call anywhere in your syntax, a mixin can only show up as its own line of code.
Unlike variables, a mixin can combine many lines of code into one neat little property that you can plug into your CSS whenever you need it.
The syntax for a mixin is exactly like standard CSS, for example:
.brown-link {
a {
padding: 1em;
background-color: @brown;
color: white;
}
a, a:hover {
background-color: @orange;
color: @brown;
}
}The difference is that, instead of having to retype all this code whenever you need a brown link in your document, you’d simply call that mixin in your code for the area that you’re working on, like so:
#Menu ul>li {
float: left;
margin-right: 1em;
.brown-link;
}Mixins work best for bits of unwieldy code you use all the time, such as font designations, CSS3 variables that require multiple lines of code, and anything else you find yourself typing over and over again. They’re also good for properties that may change as you work. I set up font conventions as mixins in the top of my .less file using a generic font stack, and change the font stack when I’ve decided which fonts I’m going to use.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access