One of the challenges when using CSS positioning for web page layout is that some of your elements may overlap others. This works fine if you want the last element in the HTML to be on top, but what if you dont’? In order to change the way elements overlap you need the
z-index property of CSS.
If you’ve used a program like MS Paint or the graphics tools in Word and PowerPoint then, chances are, you’ve seen something like
z-index in action. In these programs, you can highlight the object(s) that you’ve drawn, and choose an option “Send to back” or “Bring to front.” This is setting the
z-index of those objects.
When you’re using CSS positioning to position elements on the page, you need to think in three dimensions. There are the two standard dimensions: left/right and top/bottom. But there is also the stacking order. Each element on the page can be layered above or below any other element. The
z-index property determines where in the stack each element is. I like to think of the elements as pieces of paper, and the web page as a collage. Where I lay the paper is determined by positioning, and how much of it is covered by the other elements is the
z-index is a number, either positive (e.g. 100) or negative (e.g. -100). The default
z-index is 0. The element with the highest
z-index is on top, followed by the next highest and so on down to the lowest
z-index. If two elements have the same
z-index value (or it’s not defined) the browser will layer them in the order they appear in the HTML.
How to Use
First, you need to have the
position property set, e.g.
Then, you give each element you want in your stack a different
z-index value. For example, if I have five different elements:
- element 1 — z-index of -25
- element 2 — z-index of 82
- element 3 — z-index not set
- element 4 — z-index of 10
- element 5 — z-index of -3
They will stack in the following order:
- element 2
- element 4
- element 3
- element 5
- element 1
I recommend using vastly different
z-index values to stack your elements. That way, if you add more elements to the page later, you have room to layer them in without having to adjust the
z-index values of all the other elements. For example:
- 100 for my top-most element
- 0 for my middle element
- -100 for my bottom element
You can also give two elements the same
z-index value. If these elements are stacked, they will display in the order they are written in the HTML, with the last element on top.