Dynamic responsive background images

This morning I saw a Tweet from Anselm Hannemann asking »What’s the best way to add dynamic responsive background images?« and after some quick tests I came up with the following solution.

Here is the HTML:

<div class="bg-image">
<h1>Dynamic Background</h1>

Then we add some general CSS:

.bg-image {
position: relative;
background-size: cover;
height: 20em;

And now comes the interesting part, let’s assume we use PHP and have access to the following dynamic background images and sizes we then can use in our HTML:

$image['small'] // contains the value for the small image for a post, eg. '/postid/small.jpg'
$image['big'] // contains the value for the big image for a post, eg. '/postid/big.jpg'

Now we can add an <style> element to the <head> of our site defining the different background images for different sizes:

@media all and (min-width: 501px) {
.bg-image {
background: url(<?php echo $image['big'] ?>) no-repeat 0 0;
@media all and (max-width: 500px) {
.bg-image {
background: url(<?php echo $image['small'] ?>) no-repeat 0 0;

By using min-width and max-width media queries we ensure that only the appropriate image is loaded. For more info see this test by Tim Kadlec.

In this example, I used PHP (yes old style, but simplest for me to set up the tests), but you can use this technique also with other languages and also on static sites (eg. Jekyll).

I also put together a demo on jsbin to demonstrate it. If you find any disadvantages or improvements of this technique please let me know on twitter.

Back to top