DEV Community

Garvit Motwani
Garvit Motwani

Posted on โ€ข Edited on

5 2

Z Index in CSS

Hey Guys, I am Garvit Motwani. In This article i will tell you about the z-index property in CSS.

What is a Z Index?

The z-index property specifies the stack order of an element.

An element with greater stack order is always in front of an element with a lower stack order.

The z-index property is specified as either the keyword auto or an <integer>.

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

What does the values do?

auto
The box does not establish a new local stacking context. The stack level of the generated box in the current stacking context is the same as its parent's box.

<integer>
This <integer> is the stack level of the generated box in the current stacking context. The box also establishes a local stacking context in which its stack level is 0. This means that the z-indexes of descendants are not compared to the z-indexes of elements outside this element.

Syntax And Values

/* Keyword value */
z-index: auto;

/* <integer> values */
z-index: 0;
z-index: 2;
z-index: 300;
z-index: -1; /* Negative values to lower the priority */

/* Global values */
z-index: inherit;
z-index: initial;
z-index: unset;
Enter fullscreen mode Exit fullscreen mode

Example

HTML

<h1>The z-index Property</h1>

<img src="cat.jpg" width="100" height="140">

<p>Because the image has a z-index of -1, it will be placed behind the heading.</p>
Enter fullscreen mode Exit fullscreen mode

CSS

img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}
Enter fullscreen mode Exit fullscreen mode

This will look like this:

z-index result

HTML

<div class="dashed-box">Dashed box
  <span class="gold-box">Gold box</span>
  <span class="green-box">Green box</span>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.dashed-box { 
  position: relative;
  z-index: 1;
  border: dashed;
  height: 8em;
  margin-bottom: 1em;
  margin-top: 2em;
}
.green-box { 
  position: absolute;
  z-index: 3; /* put .green-box above .green-box and .dashed-box */
  background: green;
  width: 80%;
  left: 60px;
  top: 3em;
}
.blue-box { 
  position: absolute;
  z-index: 2; /* put .blue-box above .dashed-box */
  background: blue;
  width: 20%;
  left: 65%;
  top: -25px;
  height: 7em;
  opacity: 0.9;
}
Enter fullscreen mode Exit fullscreen mode

This one will look like this:

z-index result

Thank You Guys For Reading this article. Hopefully it helped you.

Top comments (0)

Image of Docusign

๐Ÿ› ๏ธ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more