A Small Collection Of Useful Sass Mixins

February 25, 2015

sass mixin

Everytime I create a new project, I always begin with some kind of starter-kit that includes the basics every project should have. I’m talking about an html5 index file for example, a folder structure I usually tend to use, my grunt boilerplate files etc. Today I want to share what’s in my _mixin.scss file: a selection of just four useful mixins I think every front-end developer should consider using.

Basic Reset Mixin

@mixin reset {
  margin:0;
  padding:0;
}

This is useful when resetting ul and li tags for example, or even h1 or p tags.

Clearfix Mixin

@mixin clearfix {
  &:after {
    content: "";
    display: table;
    clear: both;
  }
}

This is useful in fixing the parent collapsing around floated elements problem on the fly. A use case would be having an unordered list with its list items floating left (a menu for example), the ul will collapse. Just add this mixin to have it fixed:

ul {
  @include clearfix;
  @include reset;
  li {
    float:left;
    @include reset;
    }
}

Vertical align anything Mixin

@mixin vertical-align {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

I stole this mixin here, this is very very useful when having to center elements vertically without knowing their heights, this is something I use a lot. I’m not prefixing the transform property because I use autoprefixer for this task, if you don’t, be sure to add vendor prefixes to the mixin (chrome and webkit browsers still need the -webkit- prefix to have it working for example).

Mediaqueries Shorthand Mixin

How tedious is it to write the whole @media screen and (min-width:20em) {} everytime you have to throw a mediaquery? This is why I always use this shorthand mixin:

@mixin respond-to-min($breakpoint) {
    @media all and (min-width: $breakpoint + em) { @content; }
}

This gives you the possibility to write less and decide the breakpoint value on the fly:

div {
  width:100%;
  @include respond-to(20) {
    width:50%;
  }
}

I’m more into content-centric mediaqueries rather then deciding absolute breakpoints beforehand, so this mixin suits my needs very well. If you prefer to use pixel based mediaqueries, just change this $breakpoint + em to this $breakpoint + px. asd

These four mixins are always in my _mixin.scss file. What’s in yours? Feel free to comment.

Share this:

Back

Guest Posts

Recent Posts