JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Z- Index In CSS

Z-index & Stacking Index Explained in 3 Minutes

Mohit
JavaScript in Plain English
3 min readJul 25, 2022

--

The z-index property in CSS is used to control different layers in the document. In short, we can say higher the z-index value of an element, the higher it will appear above those having lower z-index values.

By default, when we are working with a HTML document, elements that appear lower, naturally stack above elements further.

For example:

box1,box2 & box3 without Z-Index Values
  • Let’s say we have three divs with different colors red, blue, and yellow
  • If we render the results out, box3 stacks upon box2 which stacks upon box1.

How Z-Index Behaves

To learn how stacking context works, you should position your elements with position: absolute or relative or a z-index value that's not auto.

  • In the above example if we set the position to absolute and try to set z-index: 1 on the box1, z-index: 2 on box2 & z-index: 3 on the box3, then the order of stacking will be completely reversed.
box1,box2 & box3 with Z-Index Values
  • For now, it looks quite simple, the higher z-index the higher the elements stack up. But stacking is a bit more complex than choosing a higher number.
  • Let us say we have added another small box between box2 and box3, without any z-index value the new box (green) is stacked upon box2 and below box3.

At this stage, we haven't set any z-index values on any of the boxes, and you can see how they stack up naturally

  • Now, if we set a z-index: 1 to box1, z-index: 2 to box2 & z-index: 3 to box3 & z-index: 4 to box. Our green box still stacks below…

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Responses (1)

Write a response