In this tutorial, we will learn how to effectively combine mixins and extends in SASS/SCSS to create complex yet maintainable styles. SASS/SCSS allows us to reuse and inherit styles using mixins and extends, providing a powerful way to streamline your CSS.
What you will learn:
- Understand the concept of mixins and extends in SASS/SCSS
- How to create mixins and extends
- Combining mixins and extends to create complex styles
Prerequisites:
- Basic knowledge of HTML and CSS
- Familiarity with SCSS/SASS is beneficial but not required
Understanding Mixins and Extends
- Mixins: Mixins are like functions in SASS/SCSS. They allow you to define styles that can be re-used throughout your stylesheet.
- Extends: Extends allow one selector to inherit the styles of another selector.
Creating Mixins
To define a mixin, we use the @mixin directive followed by a space and the mixin's name. Inside the curly braces {}, we place the CSS rules we want to reuse.
Creating Extends
To define an extend, we use the % character followed by a name. The CSS rules that are to be inherited are placed within curly braces {}.
Example 1: Creating and Using Mixin
// Define a mixin
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}
.box {
@include border-radius(10px);
}
This code defines a mixin called border-radius that applies a border radius to an element. The mixin is then included in the .box class, which will have a border radius of 10px.
Example 2: Creating and Using Extends
// Define an extend
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
.message {
@extend %message-shared;
}
This code defines an extend called message-shared. The .message class then extends message-shared, inheriting its styles.
Example 3: Combining Mixins and Extends
// Define a mixin
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}
// Define an extend
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
.message {
@extend %message-shared;
@include border-radius(10px);
}
Here, we combined the mixin and extend in the .message class. This class will have a 10px border radius and will also inherit the styles of message-shared.
In this tutorial, we learned about mixins and extends in SASS/SCSS, how to create them, and how to use them to create complex styles. Combining mixins and extends can make your CSS much more maintainable and concise.
Exercise 1:
Create a mixin for a transition effect and include it in a class.
Exercise 2:
Create an extend for a set of typography styles and extend it in an element.
Exercise 3:
Combine a mixin and extend in one class.
Remember, the key to mastering this is practice. So, try to incorporate mixins and extends in your stylesheets where they make sense. Happy coding!