“Cover Me!” Background-Size CSS for Large Image Backgrounds

By: • Categories: Design

While working on a few new projects recently, I needed a way to have a background image span a container (horizontally and vertically).  I tried every measure of background-size you could think of:

background-size: 100% auto;

This worked, at least until you got to smaller resolutions.  Then, the image would show the background color.

So, I tried to work out when that happened and use:

background-size: auto 100%;

But it was such a hassle to figure out when the exact break point of the image would be.

Finally, looking through some documentation last night I stumbled upon the answer.  And it’s worth sharing because It has some amazing effects if you do it right (and it’s entirely done with CSS!).

Background-size: cover

I poured through the W3C documentation and discovered that background-size has a boolean ‘cover’ option.  Instead of setting numerical values, you can have the background scale accordingly and still make sure that no color is bleeding through from the back.

A typical “covered” background image looks like this:

img{ background: url(images/background.jpg) no-repeat center center; }

Set the background image, have it to not repeat and center in the frame.

The “scrolling frame”

One of the popular visual effects in web design lately is this “scrolling frame” concept.  Imagine you have a photo, stationary on a wall.  You then cut out a hole in a piece of paper and put it over the photo.  Moving it up and down keeps the photo in one spot, but the “frame of reference” changes, so you may only see bits and pieces of the photo through the frame.   It’s an amazing effect, and it can be done with one line of CSS:

img{ background: url(images/background.jpg) no-repeat center center fixed; }

A good example can be found in the Sonnet theme by ThemeBucket.  Scroll down until you see the “blockquote” area shown below.

Beware the Bandwidth

The nice thing about these full screen backgrounds is the visual effect it brings, but make sure you’re optimizing those images.  No one wants to download a single image (or two or three or ten images) that are megabytes of data.  It’ll slow down your site and will hurt your page-ranking.