Stacking Positioned Elements

With all of the positioning going on, there will inevitably be a situation where two elements will try to exist in the same place, visually speaking. Obviously, one of them will have to overlap the other—but how do we control which one comes out “on top”?

This is where z-index comes in.

z-index allows the author to alter the way in which elements overlap each other It takes its name from the coordinate system in which side-to-side is the x-axis and top-to-bottom is the y-axis. In such a case, the third axis—that runs from front to back, or if you prefer, closer to further away from the user—is termed the z-axis. Thus, elements are given values along this axis and are represented using z-index. Figure 9-26 illustrates this system.

A conceptual view of z-index stacking

Figure 9-26. A conceptual view of z-index stacking

In this coordinate system, an element with a high z-index value is closer to the reader than those with lower z-index values. This will cause the high-value element to overlap the others, as illustrated in Figure 9-27. This is referred to as stacking.

How the elements are stacked

Figure 9-27. How the elements are stacked

Any integer can be used as a value for z-index, including negative numbers. Assigning an element a negative ...

Get Cascading Style Sheets: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.