I want to higher my quality standards of frontends and build today a little helper for the background image part:
.html
<div></div>
.scss
@mixin backgroundImage($path: '/assets/images', $fileName: null, $supports: null, $fileType: '.jpg', $unitType: 'px', $startFrom: 0) {
@each $res in $supports {
@media only screen and (min-width: $startFrom / 720 / 1280 / 1920 / 2560 / Last not need) and (max-width: $res#{$unitType}) {
background-image: url("#{$path}#{$fileName}-#{$res}#{$fileType}");
}
}
}
div {
height: 100vh;
background-size: cover;
background-repeat: no-repeat;
background-position: 50%, 50%;
background-color: navajowhite;
@include backgroundImage($fileName: 'background', $supports: (720, 1280, 1920, 2560, 3840), $startFrom: 480);
}
I tryed to create a stackblitz, but realized then, that i cant upload there images. So if you need a demo to test, please create in root where the index.html will be a folder named assets/images/
and place there 5 files named background-720
, background-1280
etc...
Ok the point is that i need here: (min-width: $startFrom / 720 / 1280 / 1920 / 2560 / Last not need)
to get in every @each
the number of $supports
of the last @each
. Just in the first @each
i need to use the $startFrom
I know its confusing. But I never wrote complex SCSS Mixins before. I hope someone can help me with that.
Okay i got it now... The final working code:
@mixin resBgImg($path: '/assets/images/', $fileName: null, $resolutions: null, $fileType: '.jpg', $unitType: 'px', $startFrom: 0)
@for $i from 1 through length($resolutions)
$min: $startFrom
@if $i > 1
$min: nth($resolutions, $i - 1)
$max: nth($resolutions, $i)
@if $i == length($resolutions)
@media only screen and (min-width: $min + 1+$unitType)
background-image: url("#{$path}#{$fileName}-#{$max}#{$fileType}")
@else
@media only screen and (min-width: $min + if($i > 1, 1, 0)+$unitType) and (max-width: $max+$unitType)
background-image: url("#{$path}#{$fileName}-#{$max}#{$fileType}")