开发者

Weird z-index behaviour preventing mouse interactions: bug or normal?

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 f开发者_高级运维ind another way?

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


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?


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; }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜