views:

135

answers:

3

I have a container (div) with a background image. In this div there is a menu - a horizontal list. What I need is to insert an image onMouseOver, positioning it absolutely, and showing it behind the text (of course!) AND on top of the div's background image. I also use jQuery, but I think this doesn't matter. The problem can be viewed online. Go to http://www.w3schools.com/css/tryit.asp?filename=trycss_zindex and paste the following text

<html>
<head>
  <style type="text/css">
    img {
      top: 0;
      left: 0;
      position:absolute;
      z-index:-1;
    }

    #main {
      color: red;
      margin: 30px;
      padding: 20px;
      width: 700px;
      min-height: 400px;
      z-index: -2;
      background-image: url("http://www.google.com/logos/mother10-hp.gif");
      background-repeat: no-repeat;
    }
  </style>
</head>

<body>
  <div id="main">
    <h1>Z-Index question:</h1>
    <img src="w3css.gif" width="100" height="140" />
    <p>How can we place the green pic between the text and the div#main?</p>
    <p>I need the green gif to appear</p>
    <ol>
      <li>On top of #main's background image</li>
      <li>Behind the text</li>
    </ol>
  </div>
</body>

</html>
+3  A: 

It seems you need position:relative;, absolute or fixed on a div for the z-index to take effect.

Jim Blackler
Thank you. It solved my problem
Raffaele
Glad I could help.
Jim Blackler
+2  A: 

Quoting the W3C:

z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Yuval A
You're right. I forgot it!! Thanks
Raffaele
A: 

I made this work for your example. Hope it helps.

<html>
<head>
  <style type="text/css">
    .img1 {
      top: 0;
      left: 0;
      position:absolute;
      z-index:2;
    }

    #wrapper {
      background-image: url("http://www.google.com/logos/mother10-hp.gif");
      background-repeat: no-repeat;
z-index:1;
width:600px;
height:600px;

    }

    #main {
      color: red;
      margin: 30px;
      padding: 20px;
      width: 700px;
      min-height: 400px;
      z-index: 3;
position:absolute;
    }
  </style>
</head>

<body>

<div id="wrapper">
    <div class="img1">
<img src="w3css.gif" width="100" height="140" />
    </div>
  <div id="main">
    <h1>Z-Index question:</h1>
    <p>How can we place the green pic between the text and the div#main?</p>
    <p>I need the green gif to appear</p>
    <ol>
      <li>On top of #main's background image</li>
      <li>Behind the text</li>
    </ol>
  </div>
</div>
</body>

</html>

You can only use z-index on positioned elements, here the wrapper is not positioned, yet it is sandwiched between the two divs. As I said, this works for the example posted, and isn't 100% accurate, you will have to add positioning for your other elements in your project. :)

Kyle Sevenoaks
Thanks, this definetly solves my problem
Raffaele
No problem, happy to help.
Kyle Sevenoaks