SCSS – @Mixins

One of the powerful features of SCSS is the ability to use mixins. Mixins are reusable blocks of code that can be included in other selectors. They can also accept arguments and return different values depending on the input. In this blog post, I will show you how to use mixins in SCSS and some examples of common use cases.

To define a mixin, you use the @‌mixin directive followed by a name and optionally some parameters. For example, here is a simple mixin that sets the font size and color of an element:

@‌mixin font-style($size, $color) {
font-size: $size;
color: $color;
}

To use a mixin, you use the @‌include directive followed by the name of the mixin and optionally some arguments. For example, here is how to apply the font-style mixin to a paragraph element:

p {
@‌include font-style(16px, blue);
}

You can also use default values for the parameters of a mixin, in case you don’t pass any arguments. For example, here is how to modify the font-style mixin to have default values of 14px and black:

@‌mixin font-style($size: 14px, $color: black) {
font-size: $size;
color: $color;
}

Now, if you use the mixin without any arguments, it will use the default values:

p {
@‌include font-style();
}

Mixins can also contain other mixins, nested selectors, media queries, and any other valid SCSS code. For example, here is a more complex mixin that creates a responsive grid layout using flexbox:

@‌mixin grid($columns, $gap) {
display: flex;
flex-wrap: wrap;
margin: -$gap;

@‌media (max-width: 768px) {
> * {
flex-basis: calc(100% - #{$gap} * 2);
}
}
}

To use this mixin, you can apply it to a container element and pass the number of columns and the gap size as arguments:

.container {
@‌include grid(3, 10px);
}

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *