CSS z-index Property Tutorial

In this section, we will learn what the z-index property is and how to use it in CSS.

Click here to run the example of z-index property

Layers in CSS: CSS z-index Property Definition and Usage

CSS z-index property

When we position multiple elements using the CSS `position` property, those elements will be at a higher level than other elements on an HTML page that follows document’s normal flow.

But two or more elements that are not positioned statically might overlap each other.

As the picture at the beginning of this section shows, overlapped positioned elements are basically stacked on top of each other toward the z-direction.

Now, CSS provided a property named `z-index` by which we can decide the placement of each positioned element in this stack.

CSS z-index Property Syntax

z-index: auto|number|initial|inherit;

CSS z-index Property Value

The value we use for this property is any positive or negative decimal number.

For example:

z-index: 1;

z-index:10;

z-index:1000;

z-index: -9;

The higher value we set for `z-index` property, the higher position the target element will have on the stack.

For example, if we have two positioned elements, the first one has the `z-index` set to 1 and the other have `z-index` set to 10. As a result, the second element with `z-index` set to 10 will be on top of the stack and audience will see that element overlapping the first element.

Note: the `z-index` property only affects elements that have `position` value other than “static” (The static value is the default value for this property).

Example: z-index in CSS

See the Pen z-index in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

Now, let’s change the value of the `z-index` property in the second element to 1, and 2 for the first element. (Basically, we’re reversing the two values set in the example above).

See the Pen the example above by Enjoy Tutorials (@enjoytutorials) on CodePen.

How Does CSS z-index Property Work?

As you can see, those that have higher values for their `z-index` property will be positioned on a higher level of the stack and so conceptually closer to the audience.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies