17Taking Mixins Further with Variables

So far, the idea of a mixin is pretty similar to what we came across in @extend—a set of attributes we apply somewhere else. With @extend, however, all values must stay the same. Mixins are more complex.

Mixins can include arguments (i.e., descriptors) that allow you to vary your values. Take the mixin we defined in the last task—blue_text. It has a set of attributes associated with it. What if you want the text size to be variable? You can easily include this in the mixin. Instead of putting a predefined font size, put $size (or whatever you wish to call it). Then, when naming your mixin, include the $size part in parentheses after the name.

When you want to use the mixin, include the argument after the mixin like you would when using a regular function.

You can also have a default value associated with a mixin. Just add the value after the variable. If you don’t specify a value when you’re using your mixin, the default will be used. If you want to change it, just add the new value like you would for a regular variable.

What To Do...
  • Define a mixin with variable attributes.
    advanced/mixin_argument.scss
     
    @mixin​ blue_text($​size​) {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: $size;
     
    font-variant: small-caps; }
  • Define a mixin with a default value.
    advanced/mixin_default.scss
     
    @mixin​ blue_text($​size​: 20px) {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: $size;
     
    font-variant: small-caps; }
  • Use a mixin with and without the default.
    advanced/mixin_default_use.scss
     
    .product_title {
     
    @include​ blue_text; }
     
     
    .product_title {
     
    @include​ blue_text (100px); }

    This compiles to:

     
    .product_title {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: 20px;
     
    font-variant: small-caps; }
     
     
    .product_title {
     
    color: #336699;
     
    font-family: helvetica, arial, sans-serif;
     
    font-size: 100px;
     
    font-variant: small-caps; }
..................Content has been hidden....................

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