When you start positioning elements in an inflexible way, like by using absolute, relative, or fixed positioning, you may need to also control the stacking order of elements.
Stacking elements also comes up with modern ways of setting layouts. It's a less legacy concept than floats or positioning, so pay attention! You may actually need this.
Consider when you're using PowerPoint, Keynote, Sketch or other software that allows you to "Send to back", "Send to back", "Forward", etc, in order to make something appear in front of or behind something else:
If you're working with a layout that was set in a legacy way, you may end up with overlapping elements. You saw elements that were accidentally overlapped in the positioning chapter, but you may want to do this on purpose too!
The CSS property z-index
will allow you to stack overlapping elements in the order of your choice. Simply give it a numerical value. The numbers you give will determine the stacking order. If you give one element a z-index
of 1 and another a z-index
of 2, the second element will appear in front of the first (the higher the value, the more "forward" it will be).
Let's take an example of three simple square cards. Right now, they appear in the same order as they appear in the HTML: from 1 to 3, where 3 is the last one (and therefore appears on top). This is the default behavior with no custom z-index
value applied:
HTML
<div id="card1">1</div>
<div id="card2">2</div>
<div id="card3">3</div>
CSS
* {
font-family: Futura;
color: white;
font-size: 1.2em;
text-align: center;
}
#card1, #card2, #card3 {
width: 200px;
height: 200px;
}
#card1 {
position: absolute;
top: 20px;
left: 20px;
background-color: #9bccdd;
}
#card2 {
position: absolute;
top: 60px;
left: 60px;
background-color: #58badd;
}
#card3 {
position: absolute;
top: 100px;
left: 100px;
background-color: #00a1e0;
}
In order to make card number 1 appear above the others, you can assign each card a z-index, where card 1's z-index is the highest. We'll set:
card 1's
z-index
to 3card 2's
z-index
to 2card 3's
z-index
to 1
#card1 {
z-index: 3;
}
#card2 {
z-index: 2;
}
#card3 {
z-index: 1;
}
In reality, you could even set these silly values:
card 1's
z-index
to 5000card 2's
z-index
to 342card 3's
z-index
to 6
The result would be the same. All that matters is how the numbers relate to one another; they don't actually have to be in order, although that does keep your code logical and easier to read!
Recap
The property
z-index
allows you to stack overlapping elements in the order of your choice.The highest
z-index
value will be visible at the top of the stack.