9

Every time I try to use z-index in a webpage to change the order of stacking overlapping divs, I seem to run into a problem where the div that is being forced lower becomes unresponsive to mouse events.

In my current situation I have:

<div class="leftcolumn">
<div class="leftbar"></div> <!-- a 95px wide bar on the left -->
...
<h3>header</h3> <!-- a little header sitting inside the leftbar
...
</div>

By default the h3 isn't showing - it's hidden behind the leftbar. If I add z-index: 5; to the h3, it still doesn't show.

So I add z-index: -1 to the leftbar. Now it's hidden behind the leftcolumn - but at least h3 shows.

So I add z-index: -2 to the leftcolumn. Now everything looks right - but you can't click on anything inside leftcolumn. The mouse cursor doesn't change from an arrow.

I get this exact behaviour in both Chrome and Firefox. IE7 doesn't show the leftbar at all, but at least stuff is clickable.

So, am I misunderstanding z-index, or is there a bug in both FF and Chrome here? Can z-index be effectively used for this kind of stuff, or do I have to find another way?

(I can change the HTML, but the less, the better.)

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

3 Answers3

7

Ok, 10 seconds later I discover that using only positive z-index'es makes the problem go away. Perhaps negative z-index means the object is below the level that the mouse cursor notionally lives?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • 6
    I can confirm that negative z-indexes disable mouse interaction in Chrome 12 and Firefox 4. IE 8 doesn't suffer from this. Using z-indexes greater than or equal to 0 enables mouse interaction. – Dan Dascalescu Aug 11 '11 at 02:31
2

Do you know that in order for z-index to work right, you need to position your elements, even if they're simply position: relative (which doesn't change their position any but allows you to use z-index). That way, you should be able to give leftbar a position of, say, 2 and your h3 a position of, say, 3. And your h3 should be on top.

You can use any position type as long as you have one.

For recap:

#leftcolumn { position: absolute; z-index: 1; }

#leftbar { position: relative; z-index: 2; }

h3 { position: relative; z-index: 3; }

Zydeco
  • 530
  • 1
  • 5
  • 11
0

Even though the leftcolumn content is visible, the leftbar div is now sitting on top of it, likely with a transparent background. Ideally you would want to modify the HTML so that the H3 resides within the leftbar, but if that is not an option, you may need to apply z-index to specific elements within the leftcolumn in order to pull them above elements in the leftbar.

kevinthompson
  • 574
  • 3
  • 15
  • Yeah, that's not really an option, because the way the code is generated, this comes out:

    blah

    some text that won't be in the leftbar

    – Steve Bennett Feb 17 '11 at 03:57