Open chrisblakley opened 5 years ago
It might be worth modifying it to only need 2 parameters (1 for the full image path, and 1 for the sizes map) and then the mixin itself could detect the last .
(using str-index
and str-slice
) to append the alternate size names. I'd just be afraid of edge-cases where it could break.
Here's what that would look like:
@mixin responsive-bg($filepath, $sizes){
background-image: url($filepath);
@if ( $sizes ){
$index: str-index($filepath, '.');
$last_index: $index;
@if ( $index ){
@for ( $i from $index + str-length('.') through str-length($filepath) ){
@if ( str-slice($filepath, $i, $i + str-length('.') - 1) == '.' ){
$last_index: $i;
}
}
}
@each $size in $sizes {
@include media($size){background-image: url(str-insert($filepath, '_' + $size, $last_index));};
}
}
}
.hero {@include responsive-bg('//gearside.com/assets/img/hero.jpg', ['sm', 'md', 'lg']);}
Note: This may break if the image path were something like this: //gearside.com/assets/img/hero.ver2.jpg
because the output would be: //gearside.com/assets/img/hero.ver2_sm.jpg
(the _sm
gets appended after the last .
no matter what which may be unexpected with those kinds of filenames.
To help with optimization, developers should be saving out large images (like hero images) at various sizes then use media queries in the CSS to load them at appropriate times. To make this easier, Nebula could provide a mixin so the developer only needs to declare the image file path once and then tell it what sizes are available.
Something like this:
The above example then pulls in the following images:
//gearside.com/assets/img/hero.jpg
//gearside.com/assets/img/hero_sm.jpg
//gearside.com/assets/img/hero_md.jpg
//gearside.com/assets/img/hero_lg.jpg