My favorite scss mixins and features

Ever since I started using SCSS/SASS, I knew I’d use this for all my future projects. It really helped me to write CSS in a meaningful way. I’m writing this post to share my favorite scss features and mixins. I use these every day for my current work.

This is not a tutorial about how to use scss. Just some very useful code snippets for scss.

  1. Mixin for media query

    This mixing help me to write responsive code for all of my projects.
    @mixin bp($feature, $value) {
    // Set global device param
    $media: only screen;

    // Media queries supported
    @if $feature == min-width{
    @media (min-width: #{$value}) {
    @content;
    }
    }@else if $feature == max-width{
    @media (max-width: #{$value}) {
    @content;
    }
    }@else{
    @media (min-width: #{$feature}) and (max-width: #{$value}) {
    @content;
    }
    }
    }

    Usage:

    * For min-width and max-width:
    * @include bp(350px ,750px)
    * For min-width:
    * @include bp(min-width, 200px)
    * For max-width:
    * @include bp(max-width, 750px)

  2. @import

    @import '_header';

    Because of Import option my codebase looks very clean. It’s very easy to use. Similar to css import with scss import you can split your css into smaller chunks. But scss @import performance is faster than css @import. Because of css @import make a http request to each @import file. But scss combines all imported files and makes one single css file.

  3. Operators
    Sass allows you to use math operators in your stylesheet. Isn’t it so cool to use maths in css ? for example:

    $width : 200;
    @if (windowSize > 640) {
    font-size: (16px / 24px); // Outputs as CSS
    width : (20px * $width);
    }

  4. @extend
    Using @extend you can re-use same styling that has been used for other component.
    This avoid you to repeat writing same thing again, also known as ‘DRY’.


    .wishlist-icon {
    color: #000;
    background-color: #fff;
    }
    .user-icon {
    @extend .wishlist-icon;
    font-size: 12px;
    }

  5. Placeholder selectors

    This also works like @extend but little bit different. This will compile only if you ever use it.
    %footer-component {
    background: black;
    font-size: 12px;
    // and so on...
    }
    .left {
    @extend %footer-component;
    color: red;
    }
    .right {
    @extend %footer-component;
    color: white;
    }

    This will compiled to :

    .right, .left {
    background: black;
    font-size: 12px;
    }

    .left {
    color: red;
    }

    .right {
    color: white;
    }

That’s it for now guys. I’ll keep updating this list whenever I find a good scss feature.
check out my other posts or leave a comment here for support. Thank you so much.

Leave a Reply

avatar
  Subscribe  
Notify of