pleasedontbelong
pleasedontbelong

Reputation: 20102

z-index not working on position absolute negative

Hi I'm making a progress bar with arrow as dividers, something like this:

HTML

<ul>
    <li>
        step 1
        <span class="arrow"></span>
    </li>
    <li>
        step 2
        <span class="arrow"></span>
    </li>
    <li>
        step 3
    </li>
</ul>

CSS

li{
    float: left;
    width: 25%;
    background-color: #4a4a4a;
    color: #fff;
    text-align: center;
    padding: 10px 0;
    position: relative;
    z-index: 100;
}
.arrow{
    width: 0;
    height: 0;
    border-top: 30px solid transparent;
    border-bottom: 30px solid transparent;
    border-left: 30px solid red;
    display: block;
    position: absolute;
    right: -30px;
    top: 0px;
    z-index: 200;
}

DEMO: http://jsfiddle.net/pleasedontbelong/kGmg5/

But the arrows are always behind the li elements. Am I missing something? Is it possible to do this without changing the html?

Upvotes: 1

Views: 9064

Answers (3)

Paulo R.
Paulo R.

Reputation: 15609

When you give an element a z-index, you create a stacking context for it. All other z-indexes on it's children will only take effect on that stacking context.

In your example, when you give your li's a z-index, you're creating a different stacking context for each of them. The arrows with the z-index will only be able to be able to get above other elements that belong to the same parent li's stacking context.

I hope I've made myself clear. But even if I did, checkout https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context . It's got some good examples.

Without changing the html, you can, as Sunil Salunkhe suggested, remove the z-index on the li's. From what it appears, there's no reason for it to be there anyway.

Upvotes: 4

Sunilosys
Sunilosys

Reputation: 19

You need to remove z-index on li:

li
{
    float: left;
    width: 25%;
    background-color: #4a4a4a;
    color: #fff;
    text-align: center;
    padding: 10px 0;
    position: relative;
    z-index: 100;
}

Upvotes: 2

John Lieb-Bauman
John Lieb-Bauman

Reputation: 1436

@Huangism is correct, the change that fixed the problem was the z-index on the li.

http://jsfiddle.net/kGmg5/9/

li{
    float: left;
    width: 25%;
    background-color: #4a4a4a;
    color: #fff;
    text-align: center;
    padding: 10px 0;
    position: relative;
    /* z-index:200;  Removed */
}

From his comment:

The right -30 is pushing the arrows behind the next li and with the z-index on the li, it creates a different stacking order

Upvotes: 2

Related Questions