DEV Community

Swarupa
Swarupa

Posted on

What is Z-Index in CSS3 and why we use it?

What is Z-index?

Z-index is a CSS property that is used to define the order or priority to stack the HTML elements. Elements with higher z-index values will be given more priority and elements with less z-index values(Negative values like -1,-2) will have less priority.

Elements with negative z-index(z-index: -1) values can be stacked under the elements with higher z-index(z-index: 1 or 99) values. Here, one important point to note about the z-index is that it only works on position values(relative, absolute, fixed, sticky) other than static and it also works on the elements of direct children of display: flex or display: grid.

Why Z-Index is ignored for the position: static?

Position: static means ignoring all the position instructions from the top, left, and z-index.

What are the possible values that we can use for Z-Index?

If we don't specify the z-index, it will take the default values as auto.

If we want to explicitly specify the z-index values using CSS selectors, we can specify them in Integer format or Global format.

- Values for Integer format:

z-index: 1; -> This will have a higher priority

z-index: -1; -> This will have a lower priority

- Values for Global format:

z-index: inherit; -> By using inherit we are telling the element to take the computed value of the property from the parent element.

z-index: initial; -> It is always set to the default value of a property to an element.

z-index: unset; -> If we use the unset property, it will set the value to a property in 2 cases. In the first case, it will check for inherited property and behave likes an inherited keyword and in the second case, it will check for initial property and behaves like an initial keyword.

let's understand with an example:

HTML:

<div class="container">
          <div class="card" id="card1"></div>
          <div class="card" id="card2"></div>
         <div class="card" id="card3"></div>
  </div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.card{
            position: relative;
            top:34px;
            border: 2px solid #000;
               }

#card1{
            position:relative;
            top:39px;
            z-index:2;
           }
Enter fullscreen mode Exit fullscreen mode

Note: As z-index works only with position(other than static), we should include position property with values in CSS styles.

Summary of Z-Index:

We can use z-index with position(relative, absolute, fixed, or sticky) and flexbox and grid. It is used to stack one element on another element.

Top comments (0)