This tutorial aims to guide you through the creation and usage of mixins in SASS/SCSS. Mixins are a powerful feature in SASS that allows you to create reusable styles that can be included in multiple places in your stylesheet.
By the end of this tutorial, you will be able to create your own mixins, include them in your SASS/SCSS styles, and understand how they can improve your CSS coding.
Basic knowledge of CSS and familiarity with SASS/SCSS syntax is assumed for this tutorial.
A mixin lets you make groups of CSS declarations that you can reuse throughout your site. You can even pass in values to make your mixin more flexible. To create a mixin, you use the @mixin
directive and include the name of the mixin.
Here's an example of a simple mixin:
@mixin reset-list {
margin: 0;
padding: 0;
list-style: none;
}
To use the mixin, you use the @include
directive followed by the name of the mixin:
ul {
@include reset-list;
}
// Define the mixin
@mixin reset-list {
margin: 0;
padding: 0;
list-style: none;
}
// Use the mixin
ul {
@include reset-list;
}
// Define the mixin
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
border-radius: $radius;
}
// Use the mixin
.box {
@include border-radius(10px);
}
In the above example, the mixin border-radius
takes an argument $radius
which is used to set the border radius of the element.
In this tutorial, you learned how to create and use mixins in SASS/SCSS. You also learned how to make your mixins more flexible with arguments. For further learning, you could explore other SASS features like variables, nested rules, and functions.
Create a mixin that accepts font-size, font-family and color as arguments and sets these properties for the element.
@mixin font-properties($size, $family, $color) {
font-size: $size;
font-family: $family;
color: $color;
}
p {
@include font-properties(16px, Arial, #333);
}
Create a mixin that accepts number of columns as an argument and creates a simple grid layout.
@mixin grid-layout($columns) {
display: grid;
grid-template-columns: repeat($columns, 1fr);
}
.container {
@include grid-layout(3);
}
In the above example, the mixin grid-layout
takes an argument $columns
which is used to create a grid layout with the specified number of columns.