Screenshot of code

Useful SASS Mixins

Since making the transition from plain old CSS to SASS a couple of years ago, I’ve found there to be a staple couple of mixins that I ensure are always included in my files at the start of a project. The five that I find most useful are….

1) Centre an element horizontally and/or vertically

//========================
//  The Mixin
//========================
@mixin center($xy:xy) {
  @if $xy == xy {
    left: 50%;
    top: 50%;
    bottom: auto;
    right: auto;
    @include transform(translateX(-50%) translateY(-50%));
  }
  @else if $xy == x {
    left: 50%;
    right: auto;
    @include transform(translateX(-50%));
  }
  @else if $xy == y {
    top: 50%;
    bottom: auto;
    @include transform(translateY(-50%));
  }
}
//=====================================
//  Using the code in your .scss file
//=====================================
.carousel {
  text-container{@include center(x);}
}

2) Retina ready background images

//========================
//  The Mixin
//========================
@mixin high-px-screens {
  @media
  only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
  only screen and (    min--moz-device-pixel-ratio: 1.3 ),
  only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
  only screen and (         min-device-pixel-ratio: 1.3 ),
  only screen and ( min-resolution: 124.8dpi ),
  only screen and ( min-resolution: 1.3dppx ){@content;}
}


//=====================================
//  Using the code in your .scss file
//=====================================
@include high-px-screens {
  #header-main {
    .logo {background: url("../images/logos/your-image@2x.png");}
  }
}

3) Using fixed media queries

//===============================
//  Define the variables first
//===============================
$lg : 1200px;
$md : 991px;
$sm : 840px;
$xs : 767px;
$xxs : 550px;

//========================
// Set up the Mixin
//========================
@mixin MQ-lg-screen {@media screen and (max-width: $lg) {@content}}
@mixin MQ-md-screen {@media screen and (max-width: $md) {@content}}
@mixin MQ-sm-screen {@media screen and (max-width: $sm) {@content}}
@mixin MQ-xs-screen {@media screen and (max-width: $xs) {@content}}
@mixin MQ-xxs-screen {@media screen and (max-width: $xxs) {@content}}

//=====================
// Using the code
//=====================
@include MQ-lg-screen {
   img {display:block; width:100%}
}

@include MQ-xs-screen {
   img {display:none;}
}

4) Styling form placeholder text

//========================
// Set up the Mixin
//========================
@mixin placeholder {
  ::-webkit-input-placeholder {@content}
  :-moz-placeholder           {@content}
  ::-moz-placeholder          {@content}
  :-ms-input-placeholder      {@content}
}

//=====================
// Using the code
//=====================
@include placeholder {
  font-style: italic;
}