Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Last active August 29, 2015 14:15
Show Gist options
  • Save rikschennink/be3d7c98b0850dbb4954 to your computer and use it in GitHub Desktop.
Save rikschennink/be3d7c98b0850dbb4954 to your computer and use it in GitHub Desktop.
Naming Media Queries

Naming Media Queries

Popular ways of naming media queries:

  • Device (mobile, tablet, desktop)
  • Size (xs ,s, m, l, xl)
  • Anonymous (alpha, beta, gamma)

I've been experimenting with naming the layouts of a module itself.

  • 2 columns
  • 3 columns
  • 4 columns

Using Sass this looks like the snippet below.

.dashboard {

  /* The available layouts for this module */
  $layouts:(
    '2 columns':30em,
    '3 columns':40em,
    '4 columns':50em
  );
  
  /* Base styles here */
  
  
  /* Two column specific styles here, they will be applied from 30em to 40em - 1px */
  @include define-layout('2 columns',$layouts) {
    
  }

  /* Three column specific styles here, they will be applied from 30em to 40em - 1px */
  @include define-layout('3 columns',$layouts) {
  
  }
  
  /* etc */
  
}

The layouts are defined locally as they are specific for this module. Also when viewing the module file you immidiately see the available layouts and when they come into effect.

The define-layout() mixin generates a media query of which the min width is the name of the layout and the max width is the next layout minus 1 pixel.

The styles within the define-layout statement create the named layout. By scoping using the min and max width (and circumventing the cascade) only those styles within the define-layout statement are used to build the desired layout.

Define layout snippet.

@mixin define-layout($name,$map) {

  /* if key not found, stop here */
  @if not map-has-key($map,$name) {
    @error 'No value found for `#{$name}`';
  }

  /* get all keys */
  $keys:map-keys($map);

  /* get from breakpoint value by layout name */
  $fromValue:map-get($map,$name);

  /* find next key */
  $current:index($keys,$name);

  /* if is top layout */
  @if $current == length($keys) {

    @media (min-width:$fromValue) {
      @content;
    }

  }
  @else {

    /* get next key */
    $next:nth($keys,$current+1);

    /* get till breakpoint value by next key name */
    $tillValue:map-get($map,$next) - (1em / 16);

    /* setup media query */
    @media (min-width:$fromValue) and (max-width:$tillValue) {
      @content;
    }

  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment