1. Technology
Send to a Friend via Email

How to Create a Background Image that Scales with the Browser Window

Responsive Designs Need Flexible Images


Resizing a background image to cover in a large window

Resizing a background image to cover in a large window

Screen shot by J Kyrnin - image © 2012 J Kyrnin

One of the first things you will discover when you start working with responsive designs and flexible-width layouts is that you need images that can adjust to the screen size as well. A while ago, I showed you how to use the CSS3 property background-size to stretch images to fit in a window, but there is an even better use for this property:

background-size: cover;

The cover keyword tells the browser to scale the image to fit the window. The image is scaled to cover the entire screen, but the original proportions and aspect ratio are kept. The image is placed in the window as large as possible so that the entire window surface is covered.

As you can see in this series of images, this results in a page that looks a lot better even if the screen is very small or very large.

How to Use background-size: cover;

Create your background image. It’s a good idea to create an image that is fairly large, as while browsers can make images smaller without a loss in quality, often when they make them larger, the images get fuzzy or blurry.

Upload your image to your web host and add it to your CSS as a background image:

background-image: url(fireworks-over-wdw.jpg);
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;

Add the browser prefixed CSS first:

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;

Then add the CSS property:

background-size: cover;

©2014 About.com. All rights reserved.