Responsive background images with just two simple Stylus mixins

On my current side project, a personal finance manager (gerenciador financeiro pessoal, in portuguese), I realized that users could wait up to 4 times less if I make the main section background image to be responsive. So, I’ve started to look for the simplest way to do that just using the powers of the CSS Preprocessor Stylus.

After some work trying different approaches to achieve it, I got the job done with just two simple mixins. The first one to handle with media queries:

if(size == ‘xs’)
@media screen and (max-width $xs-max)
else if (size == ‘xs-sm’)
@media screen and (max-width $sm-max)
else if (size == ‘sm’)
@media screen and (min-width $xs-max) and (max-width $sm-max)
else if (size == ‘sm-md’)
@media screen and (min-width $sm-min) and (max-width $md-max)
else if (size == ‘md’)
@media screen and (min-width $sm-max) and (max-width $md-max)
else if (size == ‘md-lg’)
@media screen and (min-width $md-max) and (max-width $lg-min)
else if (size == ‘lg’)
@media screen and (min-width $lg-min)

The other one to handle with background image responsiveness itself:

bg-responsive(filename, filetype)
$file-xs = filename + ‘-xs.’ + filetype;
background-image url($path-images/$file-xs)
$file-sm = filename + ‘-sm.’ + filetype;
background-image url($path-images/$file-sm)
$file-md = filename + ‘-md.’ + filetype;
background-image url($path-images/$file-md)
$file-lg = filename + ‘-lg.’ + filetype;
background-image url($path-images/$file-lg)

Now, along your code you just need call bg-responsive passing the filename and filetype for the desired image. The mixin will automatically do the rest. Obviously, you should remember to save the image in all sizes needed. Let’s use happy-couple.jpg as example. You will need four files:

happy-couple-xs.jpg (767px wide)
happy-couple-sm.jpg (959px wide)
happy-couple-md.jpg (1440px wide)
happy-couple-lg.jpg (1920px wide)

It’s important to notice that breakpoint() mixin should be call preceded by a plus sign (+). The plus sign means that the following indented lines are the content to be used as {block} inside the mixin. If you forget this, things will not work.

If you have found a simpler way to handle with responsive background-images, please, let me know.