Sunday, March 1, 2009

Multiple Background Images CSS3 and CSS2

Many times I wish to assign many background images with different settings to one html element. For example, I need to assign one image that will always be at the bottom on the left site, another one at the top on the right and one gradient below everything.
 
 
Despite the fact that CSS3 offers an easy way to do it, many browsers do not support it yet.
body{ 
   margin:0; 
   padding:0; 
   border:0; 
   font-family: Verdana; 
   font-size:10px; 
   background-image:url('bg2.gif'), url('bg3.gif'), url('bg1.jpg'); 
   background-repeat: no-repeat, no-repeat, repeat-x; 
   background-position:bottom left, top right, top;
}

In this code it is important to remember that last image will be load as first.

This works fine for Chrome 1.x and Safari 3.2. It works also ok for Konqueror 3.5 but it doesn’t support transparency in gif images. If one of the background elements is attached to the bottom this image is not rendered in Chrome 2 and Safari 4. It can be fixed by adding height:100%:

html{
    margin:0;
    padding:0;
    border:0;
    font-family: Verdana;
    font-size:10px;
    background-image:url(bg2.gif), url(bg3.gif), url(bg1.jpg);
    background-repeat: no-repeat, no-repeat, repeat-x;
    background-position: bottom left, top right, top;
    height:100%;
}

It works in Chrome 1.x, Chrome 2.x Safafi 3.2 Safari 4. An example is here.

There is also a possibility to achieve almost the same effect with CSS2 using few layers placed one above another.

<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
#wrapper1, #wrapper2, #wrapper3{ 
   padding:0; 
   margin:0; 
   border:0; 
   position:absolute; 
   top:0px; 
   left:0px; 
   right:0px; 
   bottom:0px;
}
#wrapper1{ 
   background-image:url('bg1.jpg'); 
   background-color: #FFFFAA; 
   background-repeat:repeat-x; 
   background-attachment:fixed;
}
#wrapper2{ 
   background-image:url('bg2.gif'); 
   background-position:bottom left; 
   background-repeat:no-repeat; 
   background-attachment:fixed; }
#wrapper3{ 
   background-image:url('bg3.gif'); 
   background-position:top right; 
   background-repeat:no-repeat; 
   background-attachment:fixed;
}

With small changes this style works also with IE.

#wrapper1, #wrapper2, #wrapper3{   
   width:100%;   
   height:100%;
}

A CSS2 example is here.