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:

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

The other one to handle with background image responsiveness itself:

bg-responsive(filename, filetype)
+breakpoint(‘xs’)
$file-xs = filename + ‘-xs.’ + filetype;
background-image url($path-images/$file-xs)
+breakpoint(‘sm’)
$file-sm = filename + ‘-sm.’ + filetype;
background-image url($path-images/$file-sm)
+breakpoint(‘md’)
$file-md = filename + ‘-md.’ + filetype;
background-image url($path-images/$file-md)
+breakpoint(‘lg’)
$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.