markzzz
markzzz

Reputation: 47945

Why this z-index behaviour?

This is my code :

<div id="first">
    <div id="first-internal">&nbsp;</div>
</div>

<div id="fixed">&nbsp;</div>

#first
{
    position:relative;
}

#first-internal
{
    position:relative;
    z-index:100;
    background-color:blue;
    width:400px;
    height:400px;
}

#fixed
{
    position:absolute;
    top:0;
    left:0;
    width:200px;
    height:200px;
    background-color:red;
    z-index:41;
}

Why I can't see #fixed? It is after #first, so it must have more "z-index point" then #first. The content of #fixed (also if childrens of #first have z-index:9000) must be displayed.

Upvotes: 0

Views: 316

Answers (3)

Oleg
Oleg

Reputation: 24988

It's all about stacking contexts as linked to in the css visual formatting model documentation. n the context of body:

  • #first (no z-index) qualifies as a positioned descendant with stack level 0 this element does not start a new stacking context (see below for details)

  • #fixed (z-index > 0) has a positive stack level and renders on higher

Because of that, regardless of how high you set z-index of #first decsendants, they will still remain in a lower stack relative to #first

These behaviors are identical to those of layers 6 & 7 respectively, as described in the linked documentation.

Update:

I've always found MDN docos easier to understand. Basically #first does not start a new stacking context (it is relatively positioned, but it has the default z-index:auto).

This means that #first-internal and #fixed render within the same stacking context, and the one with higher z-index is rendered on top! This is layer 6 behavior as described in the original spec linked.

Upvotes: 1

Subhajit
Subhajit

Reputation: 1987

When you make an element to position:absolute it doesn't takes any space in the document. Rather it behaves as if its floating. And its a basic nature of HTML/CSS that position:absolute objects have lesser z-index than position:relative.

This is because position:relative objects has its own existance, it doesn't float as the absolute elements.

I have posted few links below you can have a short study on these two properties :

Hope this clarifies your query.

Upvotes: -1

tibo
tibo

Reputation: 5474

The block with greater z-index should be always on top. If you read the spec you can see that putting a z-index will create a new stack context, which mean that it will basically create a layer on top of other layers with a smaller z-index, no matter the order in the HTML or css.

So in your case #fixed has a lower z-index than #first-internal, so #first-internal is on top. That's all ;)

BTW, this stack context is badly implemented in IE and it will act differently.

Upvotes: 2

Related Questions