From the Articles

Responsive fitting of elements with Sass

20th October 2014


I’m sure that, when building your user interfaces, you wished to lay items out on a grid by just specifying a number of how many of them you’d want in a row. So I wrote this mixin the other day that does just that with, say… @include fit(3) that would create a row of 3 columns, or @include fit(5) to have 5 items in a row and so on.

But what if you’d need to alter the number depending on media query? Oh well:

@include fit(1, 2, 3)

…will create a row of 1 column on small, 2 on on medium, and 3 on large screens. It’s pretty much what Foundation’s block grid does, but without Foundation. You might want to define your media queries where @include breakpoint(x) happen. Here’s the thing on Github, if you fancy that.

/**
 * Fit
 * ============================================ */

@mixin fit($small: 1, $medium: 2, $large: 3) {
  display: block;
  overflow: hidden;
  > * {
    @include box-sizing(border-box);
    height: auto;
    float: left;
    list-style: none;
    width: 100% / $small;
  }
  > *:nth-of-type(#{$small}n+1)     { clear: left; }
  > *:nth-of-type(#{$small}n)       { clear: none; }
  @include breakpoint(m) {
    > * {
      width: 100% / $medium;
    }
    > *:nth-of-type(#{$small}n+1)   { clear: none; }
    > *:nth-of-type(#{$medium}n+1)  { clear: left; }
    > *:nth-of-type(#{$medium}n)    { clear: none; }
  }
  @include breakpoint(l) {
    > * {
      clear: none;
      width: 100% / $large;
    }
    > *:nth-of-type(#{$medium}n+1)  { clear: none; }
    > *:nth-of-type(#{$large}n+1)   { clear: left; }
    > *:nth-of-type(#{$large}n)     { clear: none; }
  }
}

Like what you read? Subscribe via Email or RSS.
Have a comment? Text me on Twitter.