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;
}
}
Ich genieße diesen Mixin wirklich, aber ich frage mich, wie ich ihn mit Retina-Geräten verwenden könnte. Ist es so einfach wie das Hinzufügen einer weiteren Variable oder muss ich eine zusätzliche If-Anweisung hinzufügen?
Sehr hilfreich, danke für das Teilen!
Aber was ist, wenn meine Breakpoints verschachtelte Map-Schlüssel sind? 'map-has-key' funktioniert nur auf oberster Ebene und soweit ich verstanden habe, darf ich keine Funktion in einen Mixin einfügen.
Beispiel für eine Map
Ist das Overengineering?
@Jack, warum teilt man die Variable $structure nicht einfach in zwei verschiedene Variablen auf: $containers und $breakpoints?