Supersize that Background, Please!
Issue № 309

Supersize that Background, Please!

With an advertising world keen to use every inch of a medium for brand or product experience, it is becoming increasingly popular to design websites with full-browser backgrounds. Using CSS, this can be achieved quite easily. Just drop a huge background image in a page with one line of code (Line wraps marked » —Ed.):

Article Continues Below
body {
  background: #000 url(myBackground_1280x960.jpg) »  
center center fixed no-repeat;
}

Example one shows a centered background image of 1280 by 960 pixels that is fixed to the viewing area (it doesn’t scroll with the document).

But which image size will be big enough? Monitors and operating systems have evolved quickly, and as a result there is a wide range of available screen resolutions. The most popular resolutions today are 1024x768px, 1280x800px, 1280x1024px, and 1440x900px. However, with the advent of HD screens (1920x1080px) and professional displays that support resolutions up to 2560x1600px, almost anything is possible.

There is also a case to be made for lower resolutions. Many people resize their browser window to fill up a percentage of their screen, while a range of modern screens only support an 800x600px resolution. And that leaves a lot of lower-spec handhelds out of the equation.

Instead of using one fixed background size, a better solution would be to scale the image to make it fit within different window sizes. Unfortunately, CSS 2.1 has no means of scaling background images.

There are a couple of workarounds, however these all rely on the HTML img element (instead of CSS backgrounds). They also use absolute positioning for layering and tables or scripting to enable resizing. Additionally, not all of these techniques preserve the image’s ratio, which results in unrealistically stretched backgrounds.

CSS3 backgrounds to the rescue#section2

The W3C CSS Background and Borders Module Level 3 (currently a working draft) defines the background-size property that fits our requirements. Interesting values (to cite the W3C specs) are:

contain Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

cover Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

Contain always fits the entire image within your viewport, leaving opaque borders on either the top-bottom or the left-right whenever the ratio of the background image and browser window are not the same. In Example two, we have extended the code from Example one by setting the background-size property to contain.

Cover always fills the browser window, cutting off some hair or ears in the process, which is what I personally prefer for most cases. You can control how your image is aligned within the viewport by using the background-position property. In Example three we have extended Example one again, this time by setting the background-size property to cover.

You enable background scaling by adding the following declarations to your stylesheet:

body {
  background: #000 url(myBackground_1280x960.jpg) » 
center center fixed no-repeat;
  -moz-background-size: cover;
  background-size: cover;
}

The background-size property is already supported by Firefox 3.6 (using the -moz prefix; Firefox 4 will use the regular CSS3 property), Chrome 5, Safari 5, and Opera 10.54; and it will be included in Internet Explorer 9 (it’s already available in Preview 3). Older Webkit and Opera versions already support the background-size property, however these implementations are based on a previous draft which did not include the contain and cover keywords.

The downside of this method is that there is no background property available to set a minimum width or height. When one resizes the browser window to a very small width or height, the background image will rescale to a very small size, an often-undesired behavior.

Adding CSS3 media queries to the mix#section3

The W3C CSS3 Media Queries Module (a candidate recommendation) defines conditional rules that only apply within certain width or height ranges. This enables us to implement background scaling from a minimal width and height and on. Media queries are supported by Firefox 3.5, Chrome, Safari 3, and Opera 7, and will also be included in Internet Explorer 9.

By adding the following style rules we tell the browser that we don’t want a background image to scale smaller than 1024×768 pixels:

body {
  background: #000 url(myBackground_1280x960.jpg) »
center center fixed no-repeat;
  -moz-background-size: cover;
  background-size: cover;
}@media only all and (max-width: 1024px) and (max-height: 768px) {
  body { 
    -moz-background-size: 1024px 768px;
    background-size: 1024px 768px;
  }
}

Note that 1024x768px has the same ratio as the background image (1280x960px). When using a different ratio you will get sudden jumps in scaling when resizing your browser window.

In our final examples, four and five, we have added the @media rule, so that our background image doesn’t scale smaller than 1024 by 768 pixels. Example five shows that by setting the background-position property to left-bottom instead of center-center, we can control the way the background image is aligned within the viewport.

Revisiting old techniques#section4

These are exciting times for web developers, with all the browser makers working hard to implement upcoming technologies like HTML5 and CSS3. As a result, it’s time to start revisiting old techniques to see how the same things can be done in smarter, cleaner ways. While the upgrade cycles of Firefox, Chrome, Safari, and Opera are relatively short, it will be interesting to see how quickly people embrace Internet Explorer 9, so we can start using many of these new techniques on a large scale soon.

48 Reader Comments

  1. While this is minor if someone really needs something like this i do wonder why the scrolling of the page gets slower? Have anyone noticed that? In the first example the scrolling of the page is really smooth. In the rest of the examples scrolling isn’t that smooth,

  2. “Note that 1024x768px has the same ratio as the background image (1280x760px).”

    This is plainly false – 1024×768 is 4:3, 1280×760 is a little over 16:9

  3. Oops, that’s a typo, the examples use an image of 1280x960px (and not 1280x760px). We will fix it, thanks for catching this.

  4. Like tsiger, I noticed Firefox 3.6/Mac experiences heavy lag when scrolling or resizing the window in Example 5 of the article. It may simply be a Firefox thing (not the fastest browser anymore), but it really is a deal-breaker.

    Fortunately, I’m not too terribly anxious to make use of background-size on any commercial projects before Firefox 4 is slated to be released. 😉

  5. “it will be interesting to see how quickly people embrace Internet Explorer 9, so we can start using many of these new techniques on a large scale soon.”

    This, for me, is the crux of the matter…despite all the advances, IE still holds us back. Some things never seem to change.

  6. Hmm, I’m running the examples in Firefox 3.6.6 on Mac OSX/10.6.4 (on a relatively new MacBook Pro), however don’t notice any lags when scrolling or resizing.

  7. Yes, it is missing in the snippet. Like John Cleese once said (in How to irritate people): Sorry sir, I’ll kick myself for that!

  8. I am using Mac OS X 10.6.4 w/ Firefox 3.3.6
    I am referring to scrolling with the scrolling wheel not by grabbing the scrollbar.

    I tried to reproduce this behavior in a PC (WinXP/Firefox 3.5.10) but it works smoothly.

    I also tried with 3 different mice to eliminate any hardware issues but i do get the lag with all of them.

  9. An interesting read – Thanks.

    I can also notice a problem when scrolling using FF. I’m comparing example 1 and 4. It’s less or a ‘slow’ problem and more of a ‘jittery’ problem.

    I can probably scroll just as quickly in both, but example 4 is definitely less smooth. However, I probably wouldn’t have paid any attention to it if I hadn’t been looking for it!

    As I said, an interesting read – I like the fact that this is coming into the realm of actual possibility now that IE9 is on the way (user take-up dependant of course).

    I do find it a little worrying though that there is no mention of bandwidth/file size in your article. There are still plenty of people out there with slower connections, especially in today’s mobile-driven world.

  10. I left smallscreens out of the scope of this article, because I wanted to focus on the sizing technique only.

    There are already many great mobile articles out there that explain how you can use mobile style sheets and Media Queries to target mobile browsers. And of course you can mix these different techniques to fit your project.

  11. I’m using Firefox 3.6.6 with no extensions, and I can reproduce the slowness when using the scroll wheel.
    I’m 99% sure it’s related to the “Use smooth scrolling” setting (Options > Advanced > General).
    I don’t know what the default value for this setting is.

  12. Very cool!

    You could probably also use media queries to select different background-images depending on the resolution. This would prevent a 1024 x 768 display from downloading an enormous 2560 x 1600 image. However, I suppose that creates the new problem of (potentially) downloading additional images as the browser is resized.

    Any experience with this?

  13. @Kyle: Indeed, in that case the browser would download additional images as you resize it, something you should avoid.

    Personally I prefer to use one single image with a size somewhere in the middle (like in the examples). This way you can scale up and down depending on the required viewport size.

    This has two advantages:

    1. The quality loss is small when you scale up (better than only scaling up from e.g. an image of 800×600 px)

    2. You can better use it as a fallback image for browsers that don’t support the background-size property

    As a note on huge resolutions, how many people would resize their browser window to the full resolution? Not many, I think.

  14. Running the examples on an old Mac Mini with Firefox 3.6.6 on Mac OSX/10.6.4 I can reproduce the lag when using the scrollwheel. So I think we may conclude that in Firefox on Mac OSX the background-size property is a taxing property, and that this becomes noticeable with lower specs hardware.

  15. I have the super slow scroll like other users.

    I think the problem lies in how fast the processor is because I only have the problem on older slower pc’s & mac’s.

    The problem doesn’t change with check or un-check smooth scroll in the options tab or when using the smoothwheel FF add-on.

    If everyone wants to dig in and solve the problem I will be happy to layout the specs on 1 slow xp laptop, 1 slow quicksilver 733 mac & 1 above average speed dell.

    It very annoying and depending on the site I actually take the time to block the specif background image from loading.

  16. Sorry to overtake the comments with the Firefox bug issue. To be clear, the article was well-written, informative, and the first place I’ll go when I need to achieve something like this. Thanks for the great article!

    I’m not completely convinced that the Firefox slowness bug is related directly to hardware. I could be incorrect about this, but I don’t feel that my 1-year-old MacBook Pro (2.53 GHz, 4gb RAM) is really lacking so dramatically in the hardware department (of course, who really wants to admit that their hard-earned hardware is sub-par? ;).

    I wonder if it’s possibly related to the operating system version as well. I’m on Leopard (10.5.8), not Snow Leopard (yet).

    Thanks for filing the bug report.

  17. bq. Background images that fill the screen thrill marketers but waste bandwidth in devices with small viewports…

    I’m not seeing how this technique saves bandwidth for small screens. Scaling down with CSS does nothing to reduce the file size of the original background image.

    You’ll need to prepare properly sized images beforehand and abuse media queries for this. Making the user potentially download multiple background images is a non-issue: What sane person resizes their browser often enough to make this a problem?

    I know: That method isn’t ideal either because it gives us a lot more work. But dropping a 1280×960 image for mobile browsers isn’t particularly efficient either. It’s double the pixels shown on a retina display–not even counting browser chrome.

    If only there were a way to cache and serve dynamically resized jpegs depending on device resolution & DPI.

  18. Firefox 3.6.6 Mac 10.5.8 The pictures only rescale to a certain point, and the text box doesn’t scale at all.

  19. I really like the look of super-sized backgrounds, but when you go from one page to the next or load dynamic content that makes the page longer or shorter, the background will also resize. This gives a jumping sensation to the background image.

    The only way I can see this as being useful is if the height of your content never changes between pages or use a different background image for each page.

  20. That would depend how you aligned your image. If the image was sent to align to the top of the page (not the center) it should not jump around.

    Not upgrading your browser should be made a capital offense so we can start using this stuff 😛

  21. Actually positioning the background to top has nothing to do with this. The background doesn’t get applied to the size of the browser window, it is applied to a content container. If your content flows below the fold, the background will continue to be resized.

  22. @hoffman_jeff: Your assumptions are incorrect. In the examples the background does get applied to the size of the browser window; the length of the content will not influence this. At least, it only influences it whether or not a scrollbar gets applied. However this type of jumping will also occur with regular backgrounds, supersized or not.

  23. @dottycom: Can you please elaborate on which examples and until what approx. resolution you scaled up to? The text box is not meant to scale.

  24. Great article. Now here’s my question. Can the same principles applied here for making a background image automatically resize be applied to an image map?

    Take my website for example. (http://jennyleighb.com)

    It is basically one main image mapped with links, but because of different browser sizes, I have it set to recognize the visitor’s resolution and direct them to one of 4 differently sized versions of the site. So I basically have 4 versions of my site in different resolutions, but it would be ideal to have one version that automatically resizes (including moving the mapped links).

    Do you think something like this is possible? Maybe using this same technique?

  25. This is a great article and it fills me with hope for how much more fun it’ll be to accomplish this in the future. In the meantime, though, “this older article of mine”:http://www.boutell.com/newfaq/creating/backgroundfill.html is still a useful solution for doing it when you must support older browsers, including IE 6, 7 and 8. The code provides an optional flag to preserve the aspect ratio if you don’t want to distort the image.

  26. The “only all and” in the media query seems superfluous. Why not

    @media (max-width: 1024px) and (max-height: 768px) { … }

    Is it needed for cross-browser compatibility?

  27. Good comment. All is the default value for media type, so why not omit it? And why use the only keyword?

    You’re right, for the example (as is) you could use the shorter version as well (although I haven’t tested this). The main reason for this is that the background-size property will be ignored by browsers that haven’t implemented them. However if you would add other (more common CSS2.1) styles to the media query you may get into cross-browser issues. So in almost all my work I am used to use the ‘longer version’, to avoid potential issues.

    The following articles have documented these cross-browser issues:
    http://dev.opera.com/articles/view/how-to-serve-the-right-content-to-mobile/
    http://dev.opera.com/articles/view/safe-media-queries/

  28. You could create a nice resizeable gradient using this + some sort of background-repeat property. The only issue I’ve gotten with any browser is lagging (FireFox).

    Another way to restrict the resizing of the background image is to actually restrict the resizing of the containing box. IE: using max-*, *, and min-* (where * = width/height) would definitely do the trick. For example:

    max-width: 1000px;
    width: 90%;
    min-width: 400px;

    Would allow the user to resize their browser and watch the box resize unless it becomes too big or too small. The background-size can be set to ‘cover’ and it looks great.

  29. Hi, just thought I’d chime in on this one as regards Peng’s comments. You’re right about the resizing not solving the bandwidth issue – which for me is probably more important than any other concerns. If you use a really high quality bg, then you’re going to pay in terms of bandwidth and even on fast connections you might see some ugliness. One way I got around this on a project was to use some JS to change backgrounds, using a fast & slightly crappier version of the bg image as the default and once that was downloaded initiate a download of a larger version, which once completed had a callback which updated the CSS dynamically. Obviously this isn’t ideal, but its pretty easy, doesn’t use many lines of code, and can be combined with the article’s technique to pull off some pretty powerfull stuff.

    Also, just a note on performance of CSS3 rendering. I’ve noticed that this seems to break down by rendering engine. WebKit tends to kick-ass, Gecko etc not so much. For instance, start going nuts with the shadow properties on a large enough (i.e. say 600 x 600+) object and you’ll see a serious slowdown on all browsers, but particularly FF & its ilk. This and other issues don’t seem to be fully related to hardware either, since the WebKit browser on the iPhone (and I’m talking 3g here) does a great job of implimenting CSS3 animations and transitions that have choked desktop browsers (again, mostly FF) on my admitedly not very quick MacBook. Fact is that some of the cooler CSS3 effects are not yet ready for primetime and the browsers certainly haven’t been optimized for some of them yet. But once they are… Booyah!

    On another note, since we’re talking fairly cutting edge here, why not begin to explore SVG? Obviously if you have some backgrounds that are mre amenable to raster graphics (and most are probably) this wont work great. But, with some top notch SVG JS libraries out (and coming out) namely, Google’s, and notably Raphael JS we can get some pretty sweet cross browser SVG action on the CURRENT gen browsers, not to mention the possibilities of IE 9 (which will finally natively handle SVG). Having used SVG for some projects that would otherwise have required Flash or other esoteric techniques (in these comments, someone mentioned using an image- map!?) I have seen the promised land. For full-screen HD+ and mobile, SVG could be amazing. I’m crossing my fingers on IE 9, and with the leaps and bounds IE 7 & 8 made, I think MS is finally on the right track.

  30. Once again, alistapart showed os how to write a usefull and interesting article!

    Hot: The many usefull examples in this article, mixed up with the explanations – It’s a hell of a good cocktail!

    Not: Does not work in IE! Please, focus a bit more on ways to fix problems like that!

    “Bobby, thanks for writing this great article! Hope the feedback was helpful!”

  31. It’s not working properly in IE8. The background stretches vertically but it won’t stretch horizontally across the window.

  32. I’ve actually been using the “img” element for a while, and it’s a great workaround. You don’t need scripting at all for resizing, so I’m curious what “img” method you’re referring to. Mine usually looks something like this, with the “bg” div coming before your “wrapper” div:

    Then, my CSS is simply:
    img.bgScale
    {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index:1000;
    }

    The image only scales according to the browser width, so it’s always the proper ratio. As said above, no tables or scripting necessary, and no scrolling issues at all.

    An example: http://benpaddockdesign.com/

    Now, I know on my site the image is a huge file and rather tall, so it has extra scrolling, but that’s a conscious decision. It doesn’t have to be that way if you don’t want it to be.

    I know this is a late post, but I hope it helps.

  33. For now im using a jquery plugin that dynamically resizes the image for different screen sizes. works pretty well across all browsers.

    you can find it at ajaxbender

  34. Is there a reason to apply background-size to the body tag as opposed to the html tag? By my understanding, the html tag is always at least the size of the browser window, whereas the body tag can be smaller than the browser window, depending on explicit sizing / size of internal elements.

    If this is the case, is there a reason that we wouldn’t apply the style to the html tag, to ensure full-bleed?

    Thanks!

  35. I enjoied the article very much. It offers a great, futureproof, solution for the background. Often I like to have a fixed background for the container only. Is this also possible and if yes, how can I do this?

Got something to say?

We have turned off comments, but you can see what folks had to say before we did so.

More from ALA

I am a creative.

A List Apart founder and web design OG Zeldman ponders the moments of inspiration, the hours of plodding, and the ultimate mystery at the heart of a creative career.
Career