What is Z-Index in CSS

What is z-index

When you’re using CSS positioning to position elements on the page, you need to think in virtual 3-D. Each element on the page can be layered on top or beneath any other element. The z-index determines where in the stack each element is. I like to think of the elements as pieces of paper, and the Web page is a collage. Where I lay the paper is determined by positioning, and how much of it shows through the other elements is the z-index.

The higher a z-index value is, the more likely it will be on top when the page displays. A z-index can be negative. This tells the browser to put it lower than other elements on the page (with lower negative numbers being lower on the stack).

How to Use z-index

Use z-index with any element that you have position information on. You need to have the position attribute set, usually to position:absolute; But the specification says that z-index will work with relatively positioned elements as well.

I’ve created a simple page with several div elements positioned on top of one another. Take a look at the CSS to see the positioning and z-index values I used. I like to use widely different z-index values, such as:

  • 100 for my top-most element
  • 0 for my middle element
  • -100 for my bottom element

That way, if I decide I need additional elements stacked in other places, I can still stack them.

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.a

You may also like...