Helpful SASS/LESS Mixins

Mixins are one of the most helpful and powerful features of SASS/SCSS/LESS. Being able to define a block of code like a function in JavaScript and use that over and over again in your stylesheets is awesome. Being able to make changes in just one place or being able to calculate values or pass values to your mixin makes them very extendable. Here are some of the most useful mixins that I use daily.

While these are specifically written for SASS they can easily be adapted to LESS.

border-box

Any time there are multiple vendor-prefixed conditions to be included for one specific property means it’s perfect for a mixin. Using border-box is one of these examples.

@mixin border-box {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

border-radius

border-radius is another property that requires several vendor-prefixed properties to accommodate older browsers.

@mixin border-radius($radius) {
    -moz-border-radius: $radius;
    -ms-border-radius: $radius;
    -webkit-border-radius: $radius;
    border-radius: $radius;
}

clearfix

Whenever you’re floating elements on the page you lose that block of height because it’s taken out of the general flow of the page. Therefore you can force the height of the parent element with this mixin.

@mixin clearfix {
    &:before, &:after {
	content: " ";
	display: table;
    }

    &:after {
	clear: both;
    }
}

img-responsive

Today if a site isn’t response in some way the user experience suffers so much they’ll likely leave. Until more browsers can support tags like <picture> we need a way to change the width of images based on screen width. This mixin allows us to always force the picture to be as large as it’s container element while maintaining aspect ratio, making sure not to enlarge the image past it’s 100% width.

@mixin img-responsive {
    height: auto;
    max-width: 100%;
}

list-reset

It’s standard practice to use unordered lists for navigation and other elements on the page. Instead of constantly repeating the same code over and over each time you use a list you can include this into a helpful mixin. This works with both ordered and unordered lists.

@mixin list-reset {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

opacity

There’s a trend with a lot of these mixins where in order to support older browser vendor-prefixed properties are required. This is no exception and will allow you to use the opacity property.

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

There are hundreds of helpful mixins but these are ones I use in every project. Post in the comments below what mixins you can’t live without!

Pin It
Read More Leave comment