Site icon Treehouse Blog

3 Quick Tips for Less Repetition in Stylesheets

When you hear the word “Sass,” what comes to mind? For a lot of people it’s the most popular CSS precompiler to date. Sass takes vanilla CSS and adds variables, nesting, functions, math and more to your stylesheets. With Sass, a front-end coder can start thinking more like a programmer.

Think DRY

DRY (Don’t Repeat Yourself) is a principle of coding in which you try to repeat yourself as little as possible. Sass makes this possible within CSS. Here are three quick techniques that will make your Sass DRYer.

  1. Store color variables
    Variables let you store information to use again and again throughout your stylesheet. This comes in handy for things like brand colors.
    // Color variables
    $brand-color: #123123;
    
    // Sass Usage
    a { color: $brand-color; }
    
    // Compiled CSS
    a { color: #123123; }
  2. Create a simple mixin
    Mixins let you reuse style patterns that can be customized by passing them arguments. Mixins have many use cases, but a simple one would be controlling the border-radius of an element.
    // Border radius mixin
    @mixin radius($radius) {
      -webkit-border-radius: $radius;
      -moz-border-radius: $radius;
      border-radius: $radius;
    }
    
    // Sass Usage
    .element { @include radius(10px); }
    
    // Compiled CSS
    .element { 
      -webkit-border-radius: 10px;
      -moz-border-radius: 10px;
      border-radius: 10px;
    }
  3. Extend a placeholder class
    Placeholder classes let you reuse the same style on a bunch of elements by extending to other selectors. The extends will compile at the top of the stylesheet in a comma-separated list.
    // Font placeholder
    %base-font-styles {
      font-family: “Helvetica Neue”, Helvetica, Arial, sans-serif;
      font-weight: normal;
      color: #333;
    }
    
    // Sass Usage
    .element { @extend %base-font-styles; }
    .element-b { 
      color: #000; 
      @extend %base-font-styles; 
    }
    
    // Compiled CSS
    .element, .element-b { 
      font-family: “Helvetica Neue”, Helvetica, Arial, sans-serif;
      font-weight: normal;
      color: #333;
    }
    .element-b { color: #000; }

These three techniques open the doors to the powers of Sass and help you repeat yourself less. You’ll save hundreds of lines of code as you learn more about Sass.

If you are a front-end developer or coder and write stylesheets, stop writing vanilla CSS and learn Sass. We’ve got courses specifically tailored for learning Sass. You can start your Treehouse trial today and learn free for 14 days!

Start Learning for Free Today!

Exit mobile version