Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How does z-index actually work? Does it function on elements with no specified position? Does it favor elements (i.e. make them on top) that have a specified position?

Do the numbers have to be negative like this?

<div style='z-index:-2;'>below</div>
<div style='z-index:-1;'>less below</div>
<div style='z-index:0;'>on top</div>

Or not? Would all positive numbers (in increasing value) end up with the last being on the top, the middle in the middle, and the first on the bottom?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

Both negative and positive integers are allowed.

The position must be set on the element.

Before I get into those details, though, let me explain z-index from the ground up.

Every webpage is made up of what are called stacking contexts. You can think of these as, quite literally, a stack of elements. The z-index property determines the order of items in each stack, with higher z-index being placed further up.

All pages begin with a root stacking context, which builds from the root element (as you'd expect). But more stacking contexts can be created in a number of ways. One way is an absolutely positioned div; its children will be in a new stacking context.

The specs lists all of the instances that create a new stacking context. As others have stated, this includes explicitly positioned elements and will soon include elements that aren't completely opaque.

As I said before, z-index only takes effect if you explicitly set the position of the element. This means setting it to be fixed, absolute, or relative. This is best shown through example, I think.

In this example, we'd expect the blue div to be on top of the grey one given its z-index, right? But, as you can see, it's on the bottom. This is, of course, because we haven't set its position. Once we do that it displays as we'd expect. Again, you must set the position.

The specs also tell us that negative values are fine. With that said, you don't need to use negative values. It's perfectly fine to use positive integers, too. The default z-index value for an element is 0.

For the record, w3schools is a notoriously unreliable source for learning. While it can be a quick and convenient resource, there are lots of gaps in their information, and at times even wrong information. I recommend you to use more reliable sources like the Mozilla Developer Network, and also the specs themselves.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...