What's a Mixin?

Mixins are like shortcuts and reusable CSS snippets for your Less code. If you're familiar with a scripting language beyond HTML and CSS, they're almost like functions for your Less code.

After you really get used to using Mixins, you'll understand how useful and powerful they are. You can write extremely complex "CSS" quickly and with ease.

In my opinion, Less mixins are king amongst preprocessors in terms of syntax and easiness.

Table of Contents

    There's many, many different ways and reasons to use Mixins. We'll cover a basic example now, and then we will dive deeper in the next lesson!

    // Basic Less Mixin Demo
    .super-bold {
        font-weight: 900;
    }
    .post-item h2 {
        .super-bold;
        // .super-bold(); // This does the same thing!
    }
    
    /*==============================
    =            OUTPUT            =
    ==============================*/
    .super-bold {
      font-weight: 900;
    }
    .post-item h2 {
      font-weight: 900;
    }

    That's it! You can see how you can start mix and matching your shared styles.

    Mixins Without Output

    This is really nice, but say you didn't "need" the .super-bold class outputted in the final result.

    You could do:

    // Basic Less Mixin Demo
    .super-bold() {
        font-weight: 900;
    }
    .post-item h2 {
        .super-bold;
        // .super-bold(); // This still does the same thing!
    }
    
    /*==============================
    =            OUTPUT            =
    ==============================*/
    .post-item h2 {
      font-weight: 900;
    }

    This allows you to have unlimited helper mixins or "utility classes" without creating a gigantic CSS file result.