Anyone check my code about Media Quires Mixin in SCSS

I Create this Media Quires Mixin custom. Can anyone check tis code? $breakpoints: ( "sm_phone": 480px, "min_phone": 576px, "phone": 640px, "tablet": 768px, "max_tablet": 840px, "desktop": 992px, "desktop_max": 1024px, "widescreen": 1200px, "xl_widescreen": 1500px, ); @mixin breakpoint($breakpoint, $direction) { $media-query: null; @if map-has-key($breakpoints, $breakpoint) { $breakpoint-value: map-get($breakpoints, $breakpoint); @if $direction == "max" { $media-query: "(max-width: #{($breakpoint-value - 1)})"; } @else if $direction == "min" { $media-query: "(min-width: #{$breakpoint-value})"; } @else { $media-query: "(#{$direction}: #{$breakpoint-value})"; } } @else { $media-query: "(#{$direction}: #{$breakpoint})"; } @media #{$media-query} { @content; } } p { @include breakpoint(desktop, "min") { color: red; } } .class { @include breakpoint(1200px, "min") { display: block; } @include breakpoint(1200px, "max") { display: block; } @include breakpoint(phone, "min") { @include breakpoint(desktop_max, "max") { display: none; } } }
2 Replies
Kevin Powell
Kevin Powell•2y ago
You can simplify this a little bit: You might want to do a little more than just this, but it would be a decent start:
@mixin breakpoint($breakpoint, $direction: 'min') {
@if map-has-key($breakpoints, $breakpoint) {
$breakpoint-value: map-get($breakpoints, $breakpoint);

@media ( #{$direction}-width: $breakpoint-value ) {
@content;
}

}
}
@mixin breakpoint($breakpoint, $direction: 'min') {
@if map-has-key($breakpoints, $breakpoint) {
$breakpoint-value: map-get($breakpoints, $breakpoint);

@media ( #{$direction}-width: $breakpoint-value ) {
@content;
}

}
}
The $direction: 'min' is making min the default, so you don't have to include a direction and then it'll be a min-width media query. If you do include a max though, it will work. The only thing I'm not doing is supporting custom values, but you could add
@else {
@media ( #{direction}-width: $breakpoint) { ... }
}
@else {
@media ( #{direction}-width: $breakpoint) { ... }
}
If you want, and then if you used a value not in the map (say, 500px) or whatever, it would still work. The problem there is if you want to use something from your $breakpoints but have a typo, it won't catch that. The last thing I'd say is... that's a lot of breakpoints 😅 I usually just have something like this and it's more than enough:
$breakpoints: (
small: 30em,
medium: 45em,
large: 65em,
);
$breakpoints: (
small: 30em,
medium: 45em,
large: 65em,
);
Lazy_Joker
Lazy_JokerOP•2y ago
Thanks @Kevin
Want results from more Discord servers?
Add your server