Mixin zur Verwaltung von Breakpoints

Avatar of Kitty Giraudel
Kitty Giraudel am

Responsive Webdesign-Kreationen existieren oft über mehrere verschiedene Breakpoints. Die Verwaltung dieser Breakpoints ist nicht immer einfach. Ihre Verwendung und Aktualisierung kann manchmal mühsam sein. Daher besteht die Notwendigkeit eines Mixins zur Handhabung der Breakpoint-Konfiguration und -Verwendung.

Einfache Version

Zuerst benötigen Sie eine Map von Breakpoints, die Namen zugeordnet sind.

$breakpoints: (
  'small':  767px,
  'medium': 992px,
  'large':  1200px
) !default;

Dann wird der Mixin diese Map verwenden.

/// Mixin to manage responsive breakpoints
/// @author Kitty Giraudel
/// @param {String} $breakpoint - Breakpoint name
/// @require $breakpoints
@mixin respond-to($breakpoint) {
  // If the key exists in the map
  @if map-has-key($breakpoints, $breakpoint) {
    // Prints a media query based on the value
    @media (min-width: map-get($breakpoints, $breakpoint)) {
      @content;
    }
  }
 
  // If the key doesn't exist in the map
  @else {
    @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
        + "Available breakpoints are: #{map-keys($breakpoints)}.";
  }
}

Verwendung

.selector {
  color: red;
  
  @include respond-to('small') {
    color: blue;
  }
}

Ergebnis

.selector {
  color: red;
}
@media (min-width: 767px) {
  .selector {
    color: blue;
  }
}

Fortgeschrittene Version

Die einfache Version ermöglicht nur die Verwendung von min-width Media Queries. Um fortgeschrittenere Abfragen zu verwenden, können wir unsere anfängliche Map und den Mixin etwas anpassen.

$breakpoints: (
  'small':  ( min-width:  767px ),
  'medium': ( min-width:  992px ),
  'large':  ( min-width: 1200px )
) !default;
/// Mixin to manage responsive breakpoints
/// @author Kitty Giraudel
/// @param {String} $breakpoint - Breakpoint name
/// @require $breakpoints
@mixin respond-to($breakpoint) {
  // If the key exists in the map
  @if map-has-key($breakpoints, $breakpoint) {
    // Prints a media query based on the value
    @media #{inspect(map-get($breakpoints, $breakpoint))} {
      @content;
    }
  }
 
  // If the key doesn't exist in the map
  @else {
    @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
        + "Available breakpoints are: #{map-keys($breakpoints)}.";
  }
}

Verwendung

.selector {
  color: red;
  
  @include respond-to('small') {
    color: blue;
  }
}

Ergebnis

.selector {
  color: red;
}
@media (min-width: 767px) {
  .selector {
    color: blue;
  }
}