3

I created this fiddle to illustrate my problem: http://jsfiddle.net/AVxbd/

I have a menu (#container), with some links (#text1, #text2). I made a #highlighter element to highlight the link of the page the person is on a specific moment. The HTML:

<div id="container">
    <div id="highlighter"></div>
    <div id="text1">Text 1</div><div id="text2">Text 2</div>
</div>

The JavaScript:

$('#highlighter')
    .offset($('#text1').offset())
    .width($('#text1').width()
);

$('#text1, #text2').click(function(){
    $('#highlighter').animate({
        top: $(this).offset().top,
        left: $(this).offset().left,
        width: $(this).width() + "px"
    },300);
});

The problem is that the #highlighter element is displayed over the #text1 and #text2 elements. That's not what I want!

I tried to solve this with the z-index:

#container {     z-index: 1; }
#highlighter {   z-index: 2; }
#text1, #text2 { z-index: 3; }

However, that doesn't work, as you can see in the fiddle.

How can I get this to work? I want to let it look like the #text1 and #text2 element have an orange background, but because I want the highlighter to animate in width and position, I can't just give those elements a background themselves.

  • 1
    The `+ "px" ` is not explicitly needed as you didn't use it for top and left either. I think the z-index is also redundant, because the highlighter element is the first inside the container, see fiddle: http://jsfiddle.net/AVxbd/7/ (i moved the highlighter to the end, so it's the last element) – Imperative Apr 17 '13 at 12:37
  • @Imperative yeah, I just added them to be sure _that_ wasn't the problem. Thanks for pointing it out! –  Apr 17 '13 at 12:37

3 Answers3

8

Add position: relative; to #text1, #text2

http://jsfiddle.net/AVxbd/2/

z-index applies only to positioned elements.

Kaloyan
  • 7,262
  • 4
  • 32
  • 47
  • 2
    `+1` and a link to specification is always useful [CSS/Properties/z-index](http://www.w3.org/wiki/CSS/Properties/z-index) – andyb Apr 17 '13 at 12:35
2
#text1, #text2 {
cursor: pointer;
display: inline-block;
font-size: 30px;
height: 50px;
line-height: 50px;
text-align: center;
z-index: 3;
*position:relative;*

}

Add position to this class. Z-index does not work if position is not defined.

For details on position and z-index, click here.

AspiringCanadian
  • 1,595
  • 6
  • 24
  • 43
0

Just set position:relative; for #text1 and #text2

SEE DEMO

A. Wolff
  • 74,033
  • 9
  • 94
  • 155