16Keeping Code Clean with Mixins

Mixins are some of the more powerful elements of Sass. A mixin is a fragment of Sass that can easily be applied to another selector. Let’s say we require a distinct style: blue text with small caps. We need to apply this style to many selectors in our document. We don’t want to have to repeat color: #369; over and over again. This is the perfect situation for a mixin!

To define a mixin, all you need to type is @mixin, followed by the name of the mixin and then its styling.

Once we’ve defined it, we can easily use a mixin wherever we please—it’s a super-portable set of attributes. When you want to use the mixin, just type @include.

Mixins also help us keep our code semantic. We can define a mixin as blue_text, then apply it to a class with a more specific name, such as product_title.

It’s useful to have mixins in a separate style sheet, keeping your main style sheet cleaner. If this is the case, we need to use the bundling technique—put @import at the top of your main Sass file, linking in the mixins file.

Depending on whether you’re using Original Sass or SCSS, the use of mixins is slightly different. We’ve been through the SCSS way, where we describe a mixin with @mixin and use it with @include. With Original Sass, we use = before the mixin description and use + instead of the @include command.

What To Do...
  • Define a mixin.
    advanced/mixin_text.scss
     
    @mixin​ ​blue_text​ {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: 20px;
     
    font-variant: small-caps; }
  • Use a mixin.
    advanced/mixin_use.scss
     
    .product_title {
     
    @include​ blue_text; }

    This compiles to:

     
    .product_title {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: 20px;
     
    font-variant: small-caps; }
  • Use mixins in Original Sass style.

    Define these:

    advanced/mixin_useS.sass
     
    =blue_text
     
    color: #336699
     
    font-family: helvetica, arial, sans-serif
     
    font-size: 20px
     
    font-variant: small-caps

    And use this:

    advanced/mixin_useS.sass
     
    .product_title
     
    +blue_text

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset