Z-Index

Stacking Elements

When Elements Overlap

When you change the default positioning scheme (static) to relative, absolute, or fixed your page elements can start overlapping. By default the elements at the top of the HTML page will be behind elements that come further down the page. For example, take a look at the following code:

Figure 1 - HTML
<body> 
     <h1>This is a heading</h1> 
     <blockquote>This is a blockquote</blockquote> 
</body>

z-index-figure1

If the elements (<h1> and <blockquote>) overlapped, the <h1> would be, by default, behind the <blockquote>.

What is Z-Index?

Z-Index is comparable to Photoshop layers, or other programs that allow layering.  When elements start overlapping we can control which one is on top by specify a Z-Index (or layer).  This is done in CSS with the z-index property. The value of this property is a positive or negative number. Elements with higher numbers will be on top.

Figure 2 - CSS
h1{ 
     position: relative;
     z-index: 10; 
}

z-index-figure2

If the CSS in figure 2 was applied to the HTML in figure 1 it would cause the <h1> to move above the <blockquote>

Example Usage: div { z-index: 10; }

Activity Instructions

Here we will play around with the Z-Index of multiple overlapping boxes. This will help us understand how this property works. The adjacent gallery has several images that are screenshots of our finished goals. Choose one of these images to work from and change the Z-Index of each box in the CSS to match the goal image.

 

Tips for the following activity

  • Negative values are legit (ex. z-index: -10;)
  • The colored numbered boxes correlate with the box IDs in the CSS
  • The code at the very bottom of the CSS window is just for styling the boxes. This should be ignored.

HTML

CSS

JavaScript

Output


Commonly Asked Questions

t

Not Moving ...

 

The Z-Index is not effecting my element.

Answer

There could be several problems.

  1. First, validate your code to make sure an error is not the cause.
  2. Second, make sure that you have specified that your element is using an absolute, relative, or fixed position. The normal, or static, position does not use z-index.
t

Title of Question

 

This is a question

Answer

This is the answer
t

Title of Question

 

This is a question

Answer

This is the answer