Search code examples
jqueryhtmlcssimageposition

placing three background images in same position


I have three images img1.png, img2.png, img3.png with heights 600px,400px and 200px respectively. I want to place these images in same position such as img1.png in back, img2.png in middle and img3.png in front. I tried with css position attributes, but not working. I have placed images as background for three div's:

<div id="clouds1"></div>
<div id="clouds2"></div>
<div id="clouds3"></div>

<style>

#clouds1
{
    background:url('images/img1.png');
    height:600px;
    position:absolute;
    z-index:1;
}

#clouds2
{
   background:url('images/img2.png');
   height:400px;
   position:relative;
   z-index:8;

}

#clouds3
{
   background:url('images/img3.png');
   height:200px;
   position:relative;
   z-index:99;
}

</style>

How can we do this with css position attribute or using another method. please help. Thank you


Solution

  • I think you want something like this. Just add position:absolute & z-index:

    div#a {background-color:green;width:50px;height:10px;position:absolute;z-index:3;}
    div#b {background-color:red;width:50px;height:30px;position:absolute;z-index:2;}
    div#c {background-color:black;width:50px;height:50px;position:absolute;z-index:1;}
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>

    You can change the z-index to show which div tag that you want to show in front, which div to be in the middle etc.

    If you don't know what z-index does, here is an example when I set the black div to z-index:3. As you can see they are all in the same position but the black div is now in front of the other 2:

    div#a {background-color:green;width:50px;height:10px;position:absolute;z-index:2;}
    div#b {background-color:red;width:50px;height:30px;position:absolute;z-index:1;}
    div#c {background-color:black;width:50px;height:50px;position:absolute;z-index:3;}
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>

    Another extra thing mentioned by @gibberish is that the outer element which contains all 3 div should be position:absolute or position:relative. This is because the default position value for any html element when not specified explicitly is static.