Learn CSS intuitively - Z-index

Heyo! Welcome to the 2nd post of our "Learn CSS intuitively series", where we try to decipher CSS concepts in an intuitive manner - by relating those concepts to something you already know in the real world.

Today we look at "Z-Index". CSS z-index is like the ability to rearrange a stack of newspapers on a desk.

Think of a stack of newspapers as the layers of your webpage. Each newspaper represents an element on the page, and the order of the newspapers in the stack represents their stacking order.

In a stack, the newspaper on the top is the one you can see, and the ones below are hidden from view, assuming they overlap each other. Similarly, the stacking order of elements on a webpage determines which elements are visible and which ones are hidden. The default stacking order is the order in which elements show up in the HTML - the last one in HTML is at the top of the stack.

Now, let's say you want to bring a newspaper from the bottom of the deck to the top so that it is visible. You can achieve this by taking that newspaper out of the stack, moving it to the top, and placing it back into the stack. In CSS, you can achieve a similar effect by changing the z-index value of an element.

For example, you have two elements on your webpage: a header and a navigation menu. By default, the navigation menu appears above the header because it appears later in the HTML markup. However, if you want the header to appear above the navigation menu, you can give it a higher z-index value. This is like taking the header out of the stack of cards, moving it to the top of the stack.

The z-index values are numbers, and the higher the number, the closer the element will be to the "top" of the stack. So an element with a z-index of 10 will be on top of an element with a z-index of 5.

Let’s go one level up! Remember that each newspaper has several paper sheets inside it. Just like an element in HTML can have nested elements inside it. Now let’s say you want to bring just the 3rd sheet of the bottom newspaper over the top most newspaper. Can you do it? No! Because the stacking order of the sheet inside the bottom-most newspaper is governed by the stacking order of its newspaper itself. This is how z-index is also nested within elements in HTML. Unless the bottom-most newspaper itself is put on top of the stack, none of its nested sheets can show over any newspaper on top of it.

Hope this gives you starting idea to think about the z-index intuitively. You can hop over to CSSBattle and solve some targets to practice your z-index knowledge or give a further read here.

How did you like this post? What next concept would you want us to give a shot at?

Let us know on our forum or on the Twitter post.

Want to write for CSSBattle? Mail us your pitch.