menu

Building a Better Background Image

Nov 16, 2021 by Jason McKinney

Tips

As web developers, we're always adapting to changes within our industry. Everyday, the tools and techniques of our craft get better and our job becomes keeping up with these changes so our output can continue to improve.

Performance optimization has been an important driver for us when updating our approaches. Consider the background image applied to the hero at the top of this webpage. How can we improve on this basic implementation?

On a CMS-driven web site like this, we can populate the image by applying the asset url to an inline style like this:

                    
                    .
<div style="background: url('/uploads/insights/hero-image.jpg') no-repeat 50% 0">
   <p class="h1">Headline</p>
</div>
                    
                    

This is simple and it works, but it's not responsive, it doesn't support advanced image formats and the inline application would not conform to a serious content security policy.

With a little more work, we can use the <picture> element for our background images which opens up some more options:

                    
                    .
<picture class="position-absolute w-100 h-100 zindex-under">
  <!-- mobile -->
  <source media="(orientation: portrait) and (max-width: 551px)" srcset="/image-small.webp" type="image/webp">
  <source media="(orientation: portrait) and (max-width: 551px)" srcset="/image-small.jpg" type="image/jpeg">
  <!-- desktop -->
  <source srcset="/image-large.webp" type="image/webp">
  <img class="object-cover" width="100%" height="100%" src="/image-large.jpg" alt="">
</picture>
                    
                    

As shown above, we can use Bootstrap and a couple of custom styles to place this image behind our content as in the following pen:

View on CodePen

Now we have a responsive background image that our CMS users can populate easily via admin fields and we can generate the required variations using image transforms.

As with all content in our "Tips" series, we invite you to share any ideas you have about this method so we can all help each other become better developers.