Multiple Background Images for an Element in CSS

Recently, I observed an interesting issue at one of my client’s webpage. They wanted to add multiple background images to an element. Although as per this document, doing this in CSS is possible

div {
background-image: url(images/emo.jpg) url(images/icon068.gif);
}

however not all browsers support this feature.

To get around this issue, here’s what I proposed which also works cross-browser. The trick is to place a similar element inside the parent element, in our case placing a DIV inside a DIV.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">

<
head>
<
meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<
title>Multiple Background Images</title>
<
style type="text/css">

#outerDiv
{
height:100px;
width:100px;
background-image: url(images/emo.jpg);
background-repeat: repeat-x;
}
#innerDiv
{
height:80px;
width:100px;
background-image: url(images/icon068.gif);
background-repeat: repeat-x;
}

</style>
</
head>

<
body>
<
div id="outerDiv">
<
div id="innerDiv">

</
div>
</
div>
</
body>

</
html>



The output is as shown below with one image placed over the other. To overlap the parent image, change the width from 100px to 80px:

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Jeffrey said...

Excellent Tip! I had a similar issue in my ASP.NET Page

web design company said...

in web design CSS plays a common and most significant role. a web designer who is master in playing with CSS can demand remuneration in his own way.