Using two background-images with CSS

04
Jun

You may have come across the problem that you wanted to have two different backgrounds on your website. For example, you have one background-image that is centered (a big graphic that has “repeat:no-repeat”) and another image that is a gradient or a pattern that repeats itself (“repeat:repeat-x”) horizontally. In order to use two background-
images on your entire website you don’t need a DIV that has “height:100%;
width:100%;margin:0px auto;”
and so on. There’s a simple standard possibility that allows you to do exactly this.
For using two backgrounds we need to make use of two standard CSS-properties. As you know you can define a background-image for your entire website using the BODY-property. This could look like this:

body {
    background-image:url(image.jpg);
    background-repeat:no-repeat;
    background-position:center top;
    background-attachment:fixed;

/* Or as shorthand */
    background:url(image.jpg) no-repeat fixed center top;
}
There’s another CSS-property left you’ll also know: the HTML-element. This element also allows you to define a background – we will use it for our repeating background (like a gradient or a pattern). The CSS-code could be written as the following:
html {
    background-image:url(gradient.jpg);
    background-repeat:repeat-x;
    background-position:top;
    background-attachment:fixed;
}

body {
    background-image:url(image.jpg);
    background-repeat:no-repeat;
    background-position:center top;
    background-attachment:fixed;
}
That’s it. Now you have two background-images on your website without using a single DIV. This method also has the advantage that you don’t have to debug your elements because HTML and BODY are working well (for example, if you’re using a DIV with “width:100%;height:100%;”, you’ll have the problem that the DIV is “cutted” when you resize your browser-window so you have to define a second DIV with a static width or height in order to fix this problem).
In CSS3, there will be the possibility of defining multiple backgrounds so that you can do even more with one DIV.

Article postedPosted in @ 06/04/08

Comments

  1. ablemike
    — Jun 23, 12:23 AM: #1

    Been using this method for years!

    This is a huge limitation of CSS 2.
    I can not wait for the day of layered background images. there will be an explosion of design when this happens!

  2. Matthias
    — Jun 24, 10:51 PM: #2

    Yeah, I also can’t hardly wait for the upcoming CSS3 and its wonderful features. CSS2 has many limitations that need to be fixed with long workarounds or hacks so CSS3 has to do it better.