What are Sass mixins?

SASS (Syntactically Awesome Style Sheets) mixins are a way to group CSS declarations together and reuse them throughout your stylesheet. They allow you to define a set of styles and then include them in multiple places in your CSS without having to repeat the same code over and over again.

Mixins are defined using the @mixin keyword, followed by the name of the mixin, and a set of CSS declarations inside curly braces. For example, the following is a mixin that defines a set of styles for a button:

@mixin button {
    padding: 10px 20px;
    border-radius: 5px;
    background-color: #ff0000;
    color: #ffffff;
}

To use a mixin, you use the @include keyword, followed by the name of the mixin. For example, to apply the styles defined in the button mixin to a .btn class, you would write:

.btn {
    @include button;
}

You can also pass values to mixins, these are called parameters.

@mixin button($color: #ff0000, $padding: 10px 20px) {
    background-color: $color;
    padding: $padding;
    border-radius: 5px;
    color: #ffffff;
}

Then when you include the mixin, you can pass the values you want to use for the parameters:

.btn {
    @include button(#0000ff, 20px 40px);
}

Mixins can be very useful for making your CSS more modular and maintainable, especially when you're working on a large project. They allow you to encapsulate complex sets of styles and reuse them throughout your stylesheet, which can help to reduce code duplication and make it easier to update your CSS.

Continue Reading