Skip to content

Instantly share code, notes, and snippets.

@craigmdennis
Last active August 29, 2015 14:19
Show Gist options
  • Save craigmdennis/1de331ebc209a0a169ba to your computer and use it in GitHub Desktop.
Save craigmdennis/1de331ebc209a0a169ba to your computer and use it in GitHub Desktop.
Roll your own grid
// ----
// Sass (v3.4.12)
// Compass (v1.0.3)
// ----
$bp: (
snoop: 320px,
eminem: 30em,
diddy: 37.5rem,
dre: 768px,
dmx: 800px,
kanye: 900px
);
@mixin generate-grid-spans($breakpoint, $cols: 12) {
// Set the width to the passed in $breakpoint
// in case it's just a width
$width: $breakpoint !default;
// If it's a map get the value from the map
@if length( $breakpoint ) > 1 {
$map: nth($breakpoint,1);
$breakpoint: nth($breakpoint,2);
$width: map-get( $map, $breakpoint );
}
// For each column
@for $i from 1 through $cols {
// Define the classname to be overridden
// as it can't be defined within an @if @else
$bpname: "" !default;
// Don't print the breakpoint if false
@if $breakpoint != false {
$bpname: "-at-#{$breakpoint}";
}
// Generate a name based on the loop number and the breakpoint specified
// If the breakpoint is a px value then it will be 400
.grid-span-#{$i}#{$bpname} {
// Generate a percentage value for the column width
$result: percentage( $i / $cols );
width: $result;
// Only add helper classes for widths less than 100%
@if $result < 100% {
// Only calculate the opposing widths for each column (most common)
// So with 12 cols, `col-1` has a `-push-11` and `col-11` has a `-pull-1`
// At 50% both the `-push-*` and `-pull-*` are available.
// You can generate *all* the push / pull classes by having this
// within another '@for' loop for the columns.
@if $result <= 50% {
// Helper classes for reordering
&.-push-#{$cols - $i}#{$bpname} {
position: relative;
left: 100% - $result;
}
}
@if $result >= 50% {
&.-pull-#{$cols - $i}#{$bpname} {
position: relative;
left: - (100% - $result);
}
}
}
}
}
}
// Helper mixin if using maps
@mixin grid( $map, $breakpoint, $cols) {
@media (min-width: map-get($map, $breakpoint)) {
@include generate-grid-spans( ($map, $breakpoint), $cols);
}
}
.grid {
display: flex;
flex-wrap: wrap;
// Ensure colunms are 100% width by default
> [class*="grid-span-"] {
flex: 1;
}
> {
// Pass in (the breakpoint map, key), column count
@media (min-width: map-get($bp, eminem)) {
@include generate-grid-spans( ($bp, eminem), 4);
}
// Writing the map and the breakpoint twice sucks
// So use a helper mixin (defined on line 52)
@include grid($bp, dre, 12);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment