Blog Navigation

Responsive Background Image

Posted By Fabio

One of the first things you will discover when you start working with responsive designs is that you need images that can adjust to the screen size as well. While this task does not cause particular problems when an image is a foreground element part of another element such a div or the whole html elements, a headache can hit you when you try to make responsive an image which represents the background of a div or of the whole page. This is due to the fact that a background image and its container often have different sizes, proportions and aspect ratio and therefore they scale in a different way and no matter what you do, you will always end up having a background image which either does not fit to its container or it does, but with the wrong aspect ratio (which equals to distorted images).

The solution is the CSS property background-size and its cover attribute. The cover keyword tells the browser to scale the image in a way that it fits to the window at every border while keeping the original proportions and aspect ratio. Here is an example:

.some-style {
background: url(YourImageURL) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

While i have already explained how the cover attribute works, it is also important to say a word or two about the following line and its attributes:

background: url(YourImageURL) no-repeat center center fixed;

The no-repeat attribute tells the browser that we want only one session of the background image fitting to the container and it is the equivalent of:

background-repeat: no-repeat;

The center center attributes tell the browser that we want the background image being centered both in width and height in its container and it is the equivalent of:

background-position: center center;

And finally, the fixed attribute tells the browser that we want the background image to be attached to its container with a fix positioning so that it follows the container scaling accordingly; this is the equivalent of:

background-attachment: fixed;

You can see a Fiddle demo here and you can learn more about background-size here.

That Extra Tip
It is always a good idea, when it comes to background images, to create an image that is decently large, as while browsers can make images smaller without a loss in quality (retina-ready displays can be an exception to this, but we will go through that another time), often when they make them larger, the images get pixelated or blurry.