CSS

10 Best Sass Mixins for Web Developers

Currently, Sass is the most popular CSS preprocessor among web developers. It allows you to introduce programmatic logic to your CSS code and make use of advanced features such as variables, mixins, functions, inheritance, nesting, and others. Mixins are probably the most popular feature of Sass, as they let you create groups of CSS declarations that you can easily reuse whenever you need. With mixins, you can save a lot of time, avoid repetitions, and make your code more readable.

In this article, we have collected ten awesome Sass mixins that solve everyday CSS tasks web developers frequently encounter, such as applying vendor prefixes, supporting retina images, or maintaining aspect ratio. We have provided the mixins in SCSS format.

1. Add Vendor Prefixes to Any CSS Property

These days many web developers use PostCSS and Autoprefixer to add vendor prefixes to CSS properties that don’t come with sufficient browser support. However, there are still many developers who rather use Sass for that purpose. You can use the following mixin to add vendor prefixes to any CSS property:

/* SCSS */
@mixin css3-prefix($prop, $value) {
   -webkit-#{$prop}: #{$value};
   -moz-#{$prop}: #{$value};
   -ms-#{$prop}: #{$value};
   -o-#{$prop}: #{$value};
   #{$prop}: #{$value};
}

Example of Usage

This mixin takes two arguments that you need to define when you call it with the @include rule. The first is the name of the CSS property, and the second is its value.

/* SCSS */
div {
   @include css3-prefix(transform, scale3d(2.5, 2, 1.5));
}

Compiled CSS

In the compiled CSS, you will see that Sass has added all the necessary vendor prefixes to the transform property, used in the example.

/* CSS */
div {
   -webkit-transform: scale3d(2.5, 2, 1.5);
   -moz-transform: scale3d(2.5, 2, 1.5);
   -ms-transform: scale3d(2.5, 2, 1.5);
   -o-transform: scale3d(2.5, 2, 1.5);
   transform: scale3d(2.5, 2, 1.5);
}

2. Vertical Centering

Vertical alignment with CSS is hard, as it doesn’t have a property that explicitly lets you vertically align elements. The following mixin contains all the CSS declarations you need to vertically position any HTML element you want:

/* SCSS */
@mixin vertical-center {
   position: relative;
   top: 50%;
   -ms-transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   transform: translateY(-50%);
}

Example of Usage

As this mixin doesn’t take any argument, it’s pretty easy to call it. You simply need to add it to the @include rule. Don’t forget to add the parentheses after the name of the mixin.

/* SCSS */
div {
   @include vertical-center();
}

Compiled CSS

The Sass compiler simply adds the CSS declaration to the selector you want to position vertically.

/* CSS */
div {
   position: relative;
   top: 50%;
   -ms-transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   transform: translateY(-50%);
}

3. Font-Face Rule

It’s kind of annoying to add a separate @font-face rule to every custom font you want to use, especially since you need to support so many formats. With this following font-face mixin, you can make that tedious task much faster. Make sure that you use the right file path within the url() function.

/* SCSS */
@mixin font-face($name, $file) {
   @font-face {
   font-family: "#{$name}";
   src: url("../fonts/#{$file}.eot");
   src: url("../fonts/#{$file}.eot?#iefix") format("embedded-opentype"),
   url("../fonts/#{$file}.woff") format("woff"),
   url("../fonts/#{$file}.ttf") format("truetype"),
   url("../fonts/#{$file}.svg?#webfont") format("svg");
 }
}

Example of Usage

The font-face mixin has two arguments, the name of the font and the file name that will be part of the URL. You need to use the same file name with every font format (.eot, .woff, .ttf, etc.)

/* SCSS */
@include font-face("My Font", my-font);

Compiled CSS

The compiled CSS is very elegant as you can see. The Sass compiler has concatenated the URL paths and returned the proper @font-face rule.

/* CSS */
@font-face {
   font-family: "My Font";
   src: url("../fonts/my-font.eot");
   src: url("../fonts/my-font.eot?#iefix") format("embedded-opentype"), 
   url("../fonts/my-font.woff") format("woff"), url("../fonts/my-font.ttf") 
   format("truetype"), url("../fonts/my-font.svg?#webfont") format("svg");
}

4. Keyframe Animations

You can create beautiful animations with CSS using the @keyframes rule. Mastering animations is not easy by any means. Even if you are a pro, the syntax can be still hard to remember. The following keyframes mixin makes use of the @content directive that allows you to pass a bunch of CSS rules to the mixin.

/* SCSS */
@mixin keyframes($name) {
   @-webkit-keyframes #{$name} {
     @content;
   }
   @-moz-keyframes #{$name} {
     @content;
   }
   @keyframes #{$name} {
     @content;
   }
}

Example of Usage

The keyframes mixin takes one argument, the name of the animation. As the mixin uses the @content directive, you need to add the rules related to animation within the @include block.

/* SCSS */
@include keyframes(background) {
   0% {
     background: white;
   }
   50% {
     background: lightblue;
   }
   100% {
     background: royalblue;
   } 
}

Compiled CSS

The Sass compiler returns all the @keyframe declarations you need in order to run your animation smoothly in every browser.

/* CSS */
@-webkit-keyframes background {
   0% {
     background: white;
   }
   50% {
     background: lightblue;
   }
   100% {
     background: royalblue;
   }
}
@-moz-keyframes background {
   0% {
     background: white;
   }
   50% {
     background: lightblue;
   }
   100% {
     background: royalblue;
   }
}
@keyframes background {
   0% {
     background: white;
   }
   50% {
     background: lightblue;
   }
   100% {
     background: royalblue;
   }
}

5. Retina-Ready Images

Here is a great Sass mixin for supporting retina-ready images you can serve to Apple devices with a Retina Display. To use this mixin, you need to provide two versions of the same image, one in single size (1x) and one in double size (2x). You can use this mixin to provide a retina-ready background image for any HTML element.

/* SCSS */
@mixin retina-image($image, $width, $height) {
   @media (min--moz-device-pixel-ratio: 1.3),
   (-o-min-device-pixel-ratio: 2.6/2),
   (-webkit-min-device-pixel-ratio: 1.3),
   (min-device-pixel-ratio: 1.3),
   (min-resolution: 1.3dppx) {
       background-image: url($image);
       background-size: $width $height;
   }
}

Example of Usage

You need to specify three arguments for this mixin: the file path to the retina image (2x) and its width and height.

/* SCSS */
.image {
    background: url("my-image.png") no-repeat;
    @include retina-image("my-image2x.png", 1000px, 500px);
}

Compiled CSS

In the compiled CSS, you will find the proper media queries for Retina Display with all the necessary declarations.

/* CSS */
.image {
   background: url("my-image.png") no-repeat;
}
@media (min--moz-device-pixel-ratio: 1.3), 
(-o-min-device-pixel-ratio: 2.6 / 2), 
(-webkit-min-device-pixel-ratio: 1.3), 
(min-device-pixel-ratio: 1.3), 
(min-resolution: 1.3dppx) {
   .image {
     background-image: url("my-image2x.png");
     background-size: 1000px 500px;
   }
}

6. Absolute Positioning

Although it’s not particularly hard to absolutely position an element with CSS, you can save a lot of time with this mixin. It allows you to quickly specify values for the four directions: top, right, bottom, and left.

/* SCSS */
@mixin abs-position ($top, $right, $bottom, $left) {
   position: absolute; 
   top: $top;
   right: $right;
   bottom: $bottom;
   left: $left;
}

Example of Usage

To use the absolute positioning mixin, you simply need to add the values for the four directions. Don’t forget to pay attention to the order of the arguments. They follow each other in clockwise direction.

/* SCSS */
div {
   @include abs-position(100px, 100px, auto, auto);
}

Compiled CSS

The compiled CSS is pretty straightforward; it’s just a simple rule set for absolute positioning.

/* CSS */
div {
   position: absolute;
   top: 100px;
   right: 100px;
   bottom: auto;
   left: auto;
}

7. Arrow with Four Optional Directions

Even if an arrow is not the most spectacular part of a web page, we frequently need to use it. And, it’s not that easy to create it with CSS, as you need to use a certain technique that can be hard to remember. This mixin helps you quickly create an arrow with CSS. You can choose from four directions (up, down, left, right) and set the size and color of the arrow.

/* SCSS */
@mixin arrow($direction: down, $size: 5px, $color: #555) {
   width: 0;
   height: 0;
   @if ($direction == left) {
      border-top: $size solid transparent;
      border-bottom: $size solid transparent; 
      border-right: $size solid $color;
   }
   @else if ($direction == right) {
      border-top: $size solid transparent;
      border-bottom: $size solid transparent; 
      border-left: $size solid $color;
   }
   @else if ($direction == down) {
      border-left: $size solid transparent;
      border-right: $size solid transparent;
      border-top: $size solid $color;
   }
   @else {
      border-left: $size solid transparent;
      border-right: $size solid transparent;
      border-bottom: $size solid $color;
   }
}

Example of Usage

The arrow mixin takes three arguments: the direction, size, and color of the arrow. However, as the mixin also comes with defaults for the arguments (down, 5px, #555), you can also use it without specifying custom arguments. 

/* SCSS */

// without arguments (default)
div { 
   @include arrow(); 
}

// with custom arguments
div {
   @include arrow(up, 10px, #efefef);
}

Compiled CSS

Below, you can see how the compiled CSS looks like in both cases.

/* CSS */

// without arguments (default)
div {
   width: 0;
   height: 0;
   border-left: 5px solid transparent;
   border-right: 5px solid transparent;
   border-top: 5px solid #555;
}

// with custom arguments
div {
   width: 0;
   height: 0;
   border-left: 10px solid transparent;
   border-right: 10px solid transparent;
   border-bottom: 10px solid #efefef;
}

8. Media Queries for Mobile-First Design

You can find several Sass mixins for media queries all over the web. However, this mixin allows you to use media queries that support mobile-first design. In mobile-first design, we design for the smallest screen at first, then define styles for larger screens wherever it’s necessary. You can use the following mixin with three breakpoints: tablet, desktop, and large. There’s no breakpoint for mobile because that’s the size you design for by default.

/* SCSS */
@mixin breakpoint($point) {
   @if $point == large {
      @media only screen and (min-width: 1366px) {
         @content;
      }
   } 
   @else if $point == desktop {
      @media only screen and (min-width: 1024px) {
         @content;
      }
   } 
   @else if $point == tablet {
      @media only screen and (min-width: 600px) {
         @content;
      }
   }
}

Example of Usage

Here, you only need to define one argument, the breakpoint you want to use. You can choose from tablet, desktop, and large. This mixin uses the @content directive, so you need to add the related CSS rules separately, within the @include rule.

/* SCSS */
@include breakpoint(large) {
   div {
      font-size: 2rem;
      line-height: 1.4;
   }
}

Compiled CSS

As you can see below, the Sass-compiler has generated the proper media query for the screen size you want to apply these specific rules for.

/* CSS */
@media only screen and (min-width: 1366px) {
   div {
      font-size: 2rem;
      line-height: 1.4;
   }
}

9. Fixed Aspect Ratio

If you want a consistent look across different screen sizes you will find this aspect ratio mixin useful. It maintains the aspect ratio at any screen size. To use this mixin, you need two HTML elements: an outer and an inner one. The mixin calculates the aspect ratio of the two elements and maintains that at any resolution.

/* SCSS */
@mixin aspect-ratio($width, $height) {
   position: relative;
   &:before {
      display: block;
      content: "";
      width: 100%;
      padding-top: ($height / $width) * 100%;
   }
   > .inner-box {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
   }
}

Example of Usage

You need two HTML elements to make the aspect ratio mixin work. Both need to be either a block or an inline-block element.

<!-- HTML -->
<div class="outer-box">
   <div class="inner-box"></div>
</div>

In the SCSS, you need to define the aspect ratio within the arguments of the mixin and add the mixin to the outer element.

/* SCSS */
.outer-box {
   @include aspect-ratio(4, 3);
}

Compiled CSS

The Sass-compiler calculates the aspect ratio and applies it to the padding-top rule.

/* CSS */
.outer-box {
   position: relative;
}
.outer-box:before {
   display: block;
   content: "";
   width: 100%;
   padding-top: 75%;
}
.outer-box > .inner-box {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
}

10. Text Shortening

Our last mixin is quite simple to use but it can come in handy if you work a lot with text. It performs truncation on any text that overflows its containing element and adds an ellipsis (…) to the end.

/* SCSS */
@mixin text-shorten {
   overflow: hidden;
   text-overflow: ellipsis;
   white-space: nowrap;
}

Example of Usage

This mixin doesn’t take any argument, so you can add it to any element without much thinking.

/* SCSS */
div {
   @include text-shorten();
}

Compiled CSS

The compiled CSS simply applies the specified rule set to the HTML element you’ve added the mixin to.

/* CSS */
div {
   overflow: hidden;
   text-overflow: ellipsis;
   white-space: nowrap;
}

Next Steps

Sass mixins can automate and facilitate a lot of tasks that would be much harder to do in regular CSS. However, Sass also has many other features that are worth taking a look at. For starters, we have a great introduction to Sass that explains all the important things you need to know. Besides, we also have some advanced Sass tutorials you may want to check out, such as how to use Compass in your Sass projects and how to use Google Fonts with Sass.

To stay updated with the latest front-end development news and tutorials, you can follow us on Facebook and Twitter, too.

Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress