Sass (SCSS) mixins should be using in projects

Sass (SCSS) mixins should be using in projects

Online by JSC0d3
July 7, 2017 | | 541 recognitions

Writing in SCSS lets you use features that don’t exist in CSS yet like variables and nesting. The biggest feature though, in my opinion, is mixins. I’m not going to go into depth of what they are, or how they work, as there are other articles out there in the wild for that.

What I am going to do is share a few of our favorites that we use on pretty much every project we do here at Engage.

At their core, Sass mixing are blocks of code that you define once and can then re-use anywhere, if you are familiar with any programming language you can think of them as functions. A mixin can take multiple parameters and make calls to functions to in the end output CSS, and they are super useful when you want really clean and DRY code.
Some of the mixing below are already included in the Compass library, but since I prefer not to use Compass in my projects, I decided to write them myself.

Visually hide an element

When you hide an element with display: none, that prevents screen readers from reading it to the user. Sometimes that’s fine, but in other cases this will make the site hard to use for people with screen readers. Thus, we have to use another technique for hiding elements while at the same time make them accessible.
We are using the Sass placeholder selector since the output will always be the same, which enables us to reduce repetitive code in the output.

%visually_hidden {
  margin: -1px;
  padding: 0;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0);
  clip: rect(0, 0, 0, 0);
  position: absolute;


<button class="mobile-navigation-trigger">
  <b class="visually-hidden">Open the navigation</b>
.visually-hidden {
  @extend %visually_hidden;


Adding Truncation to an element isn’t as simple as it should be, although it is with this handy time saver, meaning when you include the mixin, you only have to specify your boundry with a max width value, happy days!

@mixin js_truncate($truncation-boundary) {
    max-width: $truncation-boundary;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;


There’s a lot of different clearfix hacks out there on the web. This one is created by (Nicolas Gallagher) and I’ve found it to be the most solid one. Works in IE6 and up.

%clearfix {
  *zoom: 1;
  &:before, &:after {
    content: " ";
    display: table;
  &:after {
    clear: both;


.container-with-children {
  @extend %clearfix;

Media queries

A massive time saver! You can just use pixel values but we have some default breakpoints setup that work too, another time saver while keeping your breakpoints consistent.

$breakpoints: (
    "phone":        400px,
    "phone-wide":   480px,
    "phablet":      560px,
    "tablet-small": 640px,
    "tablet":       768px,
    "tablet-wide":  1024px,
    "desktop":      1248px,
    "desktop-wide": 1440px
@mixin js_breakpoints($width, $type: min) {
    @if map_has_key($breakpoints, $width) {
        $width: map_get($breakpoints, $width);
        @if $type == max {
            $width: $width - 1px;
        @media only screen and (#{$type}-width: $width) {


.container {
    padding: 2rem;
    font-size: 1.8rem;
    @include js_breakpoints('tablet-wide') {
        padding-top: 4rem;
        font-size: 2.4rem;


They’re a pain as you have to set the style in all the separate formats, this sorts it for you.

@mixin js_placeholder {
    &.placeholder { @content; }
    &:-moz-placeholder { @content; }
    &::-moz-placeholder { @content; }
    &:-ms-input-placeholder { @content; }
    &::-webkit-input-placeholder { @content; }


textarea {  
    @include js_placeholder {
        color: $grey;

Responsive ratio

We use this for creating scalable elements (usually images / background images) that maintain a ratio.

@mixin js-responsive-ratio($x,$y, $pseudo: false) {
    $padding: unquote( ( $y / $x ) * 100 + '%' );
    @if $pseudo {
        &:before {
            @include pseudo($pos: relative);
            width: 100%;
            padding-top: $padding;
    } @else {
        padding-top: $padding;


div {
    @include js-responsive-ratio(16,9);

Set a rem font size with pixel fallback

Rem is similar to the em value, but instead of being relative to the parent element it’srelative to the font-size set in the <html>.
It has all the benefits of em but you don’t get issues with e.g (compounding) since rem is only relative to the html element. The bad part is there’s no support for rem units in IE8 and below. But with this mixin we can create a fallback to pixels when rem isn’t supported.

@function js-calculateRem($size) {
  $remSize: $size / 16px;
  @return $remSize * 1rem;

@mixin js-font-size($size) {
  font-size: $size;
  font-size: js-calculateRem($size);


span {
  @include js-font-size(14px)

Animations and keyframes

Animations are always a pain to create with all the vendor prefixes and what not. But with the help of this mixin it will boil down to just a few lines of code.

@mixin js-keyframes($animation-name) {
    @-webkit-keyframes #{$animation-name} {
    @-moz-keyframes #{$animation-name} {
    @-ms-keyframes #{$animation-name} {
    @-o-keyframes #{$animation-name} {
    @keyframes #{$animation-name} {

@mixin js-animation($str) {
  -webkit-animation: #{$str};
  -moz-animation: #{$str};
  -ms-animation: #{$str};
  -o-animation: #{$str};
  animation: #{$str};      

The first part of the mixin will add the proper vendor prefixes needed for browser compatibility. The next section sets it up to input your custom strings and properties. The final section of the mixin is where you would create your mixin name (in this case: fade-out) and define what you would like to happen at each keyframe in the animation. This example setup is very basic, and you can add changes to any percentage of the animation duration.


@include js-keyframes(slide-down) {
  0% { opacity: 1; }
  90% { opacity: 0; }

.js-article {
  width: 100px;
  height: 100px;
  background: black;
  @include js-animation('slide-down 5s 3');


As with animations, transitions also make your code quite bloated which can hurt the readability. But this is also solved by using a mixin for it.

@mixin js-transition($args...) {
  -webkit-transition: $args;
  -moz-transition: $args;
  -ms-transition: $args;
  -o-transition: $args;
  transition: $args;


a {
  color: gray;
  @include js-transition(color .3s ease);
  &:hover {
    color: black;

Cross browser opacity

This mixin ensures cross browser opacity all the way down to Internet Explorer 5. Though if you have to optomize for IE5, you have a lot bigger problems than opacity, godspeed my friend.

@mixin js-opacity($opacity) {
  opacity: $opacity;
  $opacity-ie: $opacity * 100;
  filter: alpha(opacity=$opacity-ie); //IE8


.js-faded {
  @include js-opacity(0.8);


When using ::before and ::after you’ll always need these three, so we’re saving two lines of code every time you use this.

@mixin js-pseudo($display: block, $pos: absolute, $content: ''){
    content: $content;
    display: $display;
    position: $pos;


article::after {
    @include js-pseudo;
    top: -1rem; left: -1rem;
    width: 1rem; height: 1rem;

Font styles

Take the pain out of setting styles for a font. (This assumes you have already included the font), set your fallback font once and you never have to worry again.

@mixin js-font-source($family: false, $size: false, $colour: false, $weight: false,  $lh: false) {
    @if $family { font-size: $family; }
    @if $size { font-size: $size; }
    @if $colour { color: $colour; }
    @if $weight { font-weight: $weight; }
    @if $lh { line-height: $lh; }


article {
    @include js-font-source('Source Sans Pro', Helvetica, Arial, sans-serif, 12px);

Retina Images

Add high resolution images to your site, with a fallback for devices that aren’t displaying high resolution images. When using retina images I would recommend compressing as much as possible without destroying the image. A good tool for this is TinyPNG (supports PNG and JPG).

@mixin js-image-2x($image, $width, $height) {
  @media only screen and (-webkit-min-device-pixel-ratio: 2),
    only screen and (min--moz-device-pixel-ratio: 2),
    only screen and (-o-min-device-pixel-ratio: 2/1),
    only screen and (min-device-pixel-ratio: 2),
    only screen and (min-resolution: 192dpi),
    only screen and (min-resolution: 2dppx) {
    background-image: url($image);
    background-size: $width $height;

This mixin will allow you to add a rule in the same spot as the CSS property defining the original image.


div.logo {
  background: url("logo.png") no-repeat;
  @include js-image-2x("logo2x.png", 100px, 25px);

Quick Gradients

Easily add gradients defining only start color, end color, and gradient type. Add all the gradient properties and you can choose as needed. The gradient type allows you to choose from a vertical gradient, horizontal gradient, or a radial (sphere shaped) gradient.

@mixin js-background-gradient($start-color, $end-color, $orientation) { 
    background: $start-color;

    @if $orientation == 'vertical' {
      background: -webkit-linear-gradient(top, $start-color, $end-color);
      background: linear-gradient(to bottom, $start-color, $end-color);
    } @else if $orientation == 'horizontal' {
      background: -webkit-linear-gradient(left, $start-color, $end-color);
      background: linear-gradient(to right, $start-color, $end-color);
    } @else {
      background: -webkit-radial-gradient(center, ellipse cover, $start-color, $end-color);
      background: radial-gradient(ellipse at center, $start-color, $end-color);

No longer will you have to remember the various vendor prefixes and parameter orders for implementing gradients.


.foo {
  @include js-background-gradient(red, black, 'vertical');

Quick Padding & Margins

The main reason I use this is because I will omit a specific padding property, like padding-left at times, and I don’t want to define it. Using the Sass property null, you can omit padding properties. The same rules apply for margins.

//Padding mixin
@mixin js-padding($top, $right, $bottom, $left) {
  padding-top: $top;
  padding-right: $right;
  padding-bottom: $bottom;
  padding-left: $left;
//Margin mixin
@mixin js-margin($top, $right, $bottom, $left) {
  margin-top: $top;
  margin-right: $right;
  margin-bottom: $bottom;
  margin-left: $left;

The mixing can then be used to replace a bunch of padding-* and margin-* properties throughout your stylesheets. You can quickly include this mixin in any element and define only the sides of padding/margins you want to include. Padding and margins are one of the most used CSS styles added to elements, and a small time saver like this will quickly add up.


// Usage 1
@include js-padding(1px, 2px, 3px, 4px,);
@include js-margin(1px, 2px, 3px, 4px);

// Usage 2 (with null properties)
@include js-padding(1px, null, 3px, 4px);
@include js-margin(1px, 2px, null, 4px);

Wrap Up

Using Sass mixins like the ones outlined in this article are a great way for making your workflow more efficient. Theses specific mixins will help you spend less time on common web tasks, giving you more time to focus on other aspects of the project that require more careful and skilled insight.

Installing and working with Sass can be done a number of ways, and will involve using the command prompt to install some libraries in your project. One way to install Sass is to use Ruby – as outlined on the main Sass website here – and another popular way is to use Node.js.

The benefits of Sass extend beyond automation, and can help to easily create and manage your project stylesheets. Even some of the most basic web projects can have thousands of lines of CSS code. Sass is a great way to break this code up into more manageable bits, each with their own focus.

JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | July 9, 2017

Grid systems are an incredibly powerful tool when creating any sort of website There are many grid systems out there, such as Bootstrap and Zurb...

Posted by | July 8, 2017

There are numerous advantages of WordPress SASS for WordPress developers You have most likely heard numerous contentions for utilizing a...

Posted by | August 17, 2016

A CSS rule's selector specifies which elements in your DOM the rule will apply to The contextual type, class, and id selectors match an element's tag...

Previous PostBackNext Post
30 impressions on “Sass (SCSS) mixins should be using in projects

happy days,

I actually wanted to write a quick message in order to appreciate you for all of the great recommendations you are placing on this site. My prolonged internet research has now been rewarded with extremely good points to share with my partners. I would express that we site visitors are rather fortunate to live in a magnificent network with very many awesome individuals with very beneficial basics. I feel very privileged to have discovered the website and look forward to really more brilliant times reading here. Thank you again for everything.

J&S Code,

Very nice of you happy days, thank you very much. I will try to write articles as simplistic as to make them understandable. Thank you again.

yeezy boost 350 v2,

I simply wanted to develop a quick comment so as to say thanks to you for some of the unique strategies you are posting on this website. My time consuming internet look up has finally been rewarded with extremely good points to exchange with my partners. I ‘d declare that many of us site visitors are rather blessed to be in a decent network with very many perfect individuals with great pointers. I feel extremely happy to have come across your entire web pages and look forward to plenty of more excellent times reading here. Thanks a lot once more for a lot of things.

J&S Code,

That’s very kind of you to say yeezy, thanks so much

nike roshe run,

The next time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my choice to read, but I truly thought youd have one thing interesting to say. All I hear is a bunch of whining about something that you may fix if you werent too busy looking for attention.

J&S Code,

Sorry nike, we can’t please everyone. Hope that you’ll find something useful next time!

yeezy boost,

A lot of thanks for every one of your effort on this web site. Kate take interest in setting aside time for research and it is easy to understand why. A number of us know all about the compelling ways you deliver important guides via the web site and even welcome response from people on that concern so our favorite daughter is certainly becoming educated a lot of things. Have fun with the remaining portion of the new year. You are doing a fabulous job.

J&S Code,

We’re glad you enjoyed the post, thanks so much.

adidas outlet,

Would you be curious about exchanging links?

J&S Code,

No thanks for require!

yeezy boost 350,

I wanted to write a simple note in order to thank you for these lovely items you are writing at this site. My incredibly long internet research has at the end been compensated with reliable knowledge to write about with my friends. I would tell you that most of us readers are very much lucky to live in a decent network with many awesome professionals with insightful tricks. I feel very much blessed to have encountered the website page and look forward to many more brilliant minutes reading here. Thanks once more for everything.

J&S Code,

We’re pleased you enjoyed the post, thanks so much. Happy coding!

curry 3,

An interesting dialogue is price comment. I think that it’s best to write more on this topic, it might not be a taboo subject however usually persons are not enough to talk on such topics. To the next. Cheers

yeezy shoes,

I needed to send you the little observation in order to say thanks again with the marvelous ideas you’ve featured above. This is simply shockingly generous with people like you to give easily precisely what a few people would’ve marketed as an ebook to generate some bucks for themselves, chiefly given that you might well have done it if you considered necessary. These secrets also acted to provide a great way to fully grasp some people have the same desire the same as mine to learn significantly more when it comes to this issue. I think there are several more pleasant instances ahead for individuals who see your site.

J&S Code,

That’s very kind of you to say “yeezy shoes”, thanks so much for observation

tory burch outlet,

I discovered your blog site on google and test a couple of of your early posts. Continue to maintain up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading extra from you later on!?

J&S Code,

We’re glad you enjoyed our website, thanks so much.

yeezy boost 350,

Thanks for all your efforts on this website. My mom takes pleasure in working on internet research and it’s easy to understand why. Most of us notice all concerning the powerful tactic you provide practical strategies via the website and even increase contribution from other ones on the topic plus our own girl is actually becoming educated a lot. Have fun with the rest of the year. You are carrying out a useful job.

J&S Code,

Very nice of you, thank you very much. I will try to write articles as simplistic as to make them understandable. Thank you again.

Adidas NMD Men Women Dark Green,

I want to express appreciation to the writer just for bailing me out of such a matter. Just after searching throughout the online world and finding tips which are not pleasant, I assumed my life was over. Living without the approaches to the difficulties you’ve fixed all through your main article is a critical case, and the ones which may have in a wrong way affected my career if I had not encountered your web site. That talents and kindness in maneuvering all the stuff was very helpful. I don’t know what I would’ve done if I had not come upon such a solution like this. I can now look forward to my future. Thank you very much for the expert and result oriented help. I will not think twice to refer the sites to any individual who should have guidance about this situation.

longchamp handbags,

There are some fascinating closing dates in this article but I don抰 know if I see all of them center to heart. There is some validity but I will take maintain opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as effectively

hermes belt,

There is noticeably a bundle to find out about this. I assume you made certain good points in options also.

yeezy sneakers,

Thank you a lot for giving everyone an exceptionally spectacular chance to read critical reviews from here. It really is so pleasurable and also jam-packed with fun for me and my office acquaintances to search your web site at minimum thrice weekly to see the new things you have got. And of course, I’m also always satisfied concerning the very good advice you serve. Certain two points in this posting are essentially the simplest we’ve ever had.

longchamp bags,

Can I simply say what a relief to find somebody who actually knows what theyre talking about on the internet. You definitely know how to carry a difficulty to gentle and make it important. More folks must learn this and perceive this facet of the story. I cant imagine youre not more fashionable because you undoubtedly have the gift.

adidas nmd r1,

I happen to be writing to let you be aware of what a wonderful experience my girl enjoyed browsing yuor web blog. She mastered a wide variety of issues, with the inclusion of what it’s like to have an incredible giving character to make the others completely fully grasp specified specialized subject areas. You truly exceeded my desires. Many thanks for offering such productive, trustworthy, educational and also easy guidance on that topic to Julie.

adidas superstar,

After research a couple of of the blog posts in your web site now, and I really like your way of blogging. I bookmarked it to my bookmark website listing and shall be checking again soon. Pls try my site as effectively and let me know what you think.

yeezy boost 350,

Thank you so much for providing individuals with remarkably brilliant possiblity to read from this site. It can be so pleasant and also stuffed with amusement for me and my office colleagues to visit your blog nearly 3 times a week to learn the latest guides you have. And of course, we’re at all times astounded with all the magnificent pointers served by you. Selected 4 points in this post are basically the most effective we’ve had.

mlb jerseys,

very good post, i actually love this website, carry on it

J&S Code,

We’re glad you enjoyed the post, thanks so much.

adidas yeezy boost,

I and my guys have been going through the great recommendations on your web site and then instantly I had a terrible feeling I had not thanked the web site owner for them. The women became absolutely warmed to learn them and now have quite simply been using them. Appreciate your truly being well considerate and for picking out some outstanding resources most people are really desperate to understand about. Our own sincere regret for not saying thanks to you sooner.

Leave here an impression