Table of contents
Hi!
This time I will show you how to set up breakpoints using Sass for you to use in any project.
For this we will use Sass mixins. Mixins allow you to define styles that can be re-used throughout your stylesheet.
Breakpoints
First we need to create our breakpoints. I used breakpoints values from Bootstrap page, just to refer to most common breakpoints pixel values.
$breakpoints: (
'small': 576px,
'medium': 768px,
'large': 992px,
'extra-large': 1200px,
) !default;
Mapping breakpoints
Next we need to create mapping for our breakpoints.
@mixin respond-to($breakpoint) {
@if map-has-key($breakpoints, $breakpoint) {
@media (max-width: map-get($breakpoints, $breakpoint)) {
@content;
}
}
@else {
@warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
+ "Available breakpoints are: #{map-keys($breakpoints)}.";
}
}
Usage
Now we can use our breakpoints in our code. In the example we change background-color to blue when screen width will be lower than 576px.
.container{
background-color: green;
@include respond-to('small'){
background-color: blue;
}
}
Which is the same as we would write in css
.container{
background-color: green;
}
@media (max-width: 576px) {
.container{
background-color: blue;
}
}
If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)