chrisblakley / Nebula

Nebula is a WordPress theme framework that focuses on enhancing development. The core features of Nebula make it a powerful tool for designing, developing, and analyzing WordPress websites consistently, yet its deliberately uncomplicated code syntax also serves as a learning resource for programmers themselves.
https://nebula.gearside.com
GNU General Public License v2.0
141 stars 36 forks source link

Consider a responsive background image mixin #1940

Open chrisblakley opened 5 years ago

chrisblakley commented 5 years ago

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:

@mixin responsive-bg($directory, $filename, $extension, $sizes){
    background-image: url($directory + $filename + "." + $extension);

    @if ( $sizes ){
        @each $size in $sizes {
            @include media($size){background-image: url($directory + $filename + "_" + $size + "." + $extension);};
        }
    }
}

.hero {@include responsive-bg('//gearside.com/assets/img/', 'hero', 'jpg', ['sm', 'md', 'lg']);}

The above example then pulls in the following images:

chrisblakley commented 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.