Load background images based on the screen size


Load small background images on smaller screens and large ones on larger screens.






TLDR : If all that you are interested in is code to make this work, go to this section and grab the code snippet.


Responsive Background Display isn’t Responsive Background Loading

Setting a background’s ‘background-size’ property to ‘cover’ allows us to ensure it covers the background region fully on any screen size. But, since the same image is loaded irrespective of the screen-size, this setting is responsive only in terms of image display and not in terms of the image loaded. As a result, you could have a 1400px background image loaded on a Google Nexus 4 mobile screen.


<!--Same image is loaded as page background irrespective of device screen size -->
html {
  background: url(&lsquo;large_bg.jpg&rsquo;) no-repeat center center fixed;
  background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;<br />
}


Responsive Background Image Loading

Using media queries allows us to specify different background images for different screen sizes purely using CSS. This way, background image sized according to screen size gets downloaded by the browser.


<!--Using media queries to select right sized background image to download-->
@media screen and (max-width: 480px) {
  html {
    background: url(&lsquo;small_bg.jpg&rsquo;) no-repeat center center fixed;
  }
}
@media screen and (min-width: 481px) and (max-width: 900px) {
  html {
    background: url(&lsquo;med_bg.jpg&rsquo;) no-repeat center center fixed;
  }
}
@media screen and (min-width: 901px) {
  html {
    background: url(&lsquo;large_bg.jpg&rsquo;) no-repeat center center fixed;
  }
}
html {
  background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;<br />
}</p>

<p>


Prevent Loading Hidden Element’s Background

In case if you want to ensure that background image for an element that is hidden on a certain screen isn’t downloaded, just use CSS media queries to set background to ‘none’ for that screen-size.


<!--Avoid downloading background on smaller screen-->
@media screen and (max-width: 480px) {
  html {
    background: none;
  }
}</p>

<p>

If you want to make sure you do not load hidden the images (used through <img> tag), check out this how-to.





Want to know when exactly is your website slow?

Use Tezify Speed Analytics to track how fast your website loads for your visitors and it's business impact. Uncover speed optimizations with maximum gain.


Speed Analytics icon