Stacking Elements in Layers - HTML

Using CSS positioning can often lead to elements stacked on top of one another. Usually, you can anticipate how the elements will stack and leave the user agent up to its own devices regarding the display of stacked elements. At times, however, you will want to explicitly specify how overlapping elements stack. To control the stacking of elements, you use the z-index property.

The z-index property has this format:

z-index: value;

The property controls the third dimension of the otherwise flat HTML media. Because the third dimension is typically referred to along a Z axis, this property is named accordingly (with a Z). You can think of the z-stack as papers stackedon a desktop, overlapping each other—some of the papers are covered by other pieces. The value controls where on the stack the element should be placed. The beginning reference (the document) is typically at index 0 (zero). Higher numbers place the element higher in the stack, as shown in the diagram.

The effect of the z-index property.

The effect of the z-index property.

A practical example of z-index stacking can be seen in Figure 23-13. Each element is assigned a z-index, as shown in the following code:

The code uses a mix of <div> and <p> elements for diversity. Since box1’s index is the highest (200), it is rendered on the top of the stack. Box3’s index is the next highest (150), so it is rendered second to the top. Box2’s index is the lowest (100), so it is rendered near the bottom. The document itself is recognized as being at 0, so it is rendered at the bottom of the stack.

If you change the z-index of box1 to 125, it will render under box3.

A sample of z-index stacking.

A sample of z-index stacking.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

HTML Topics