Understanding z-index

Z-index is a CSS property that is used to cascade overlapping elements in HTML. This property can be applied to those elements which have been positioned (relative, absolute, fixed). It takes integer values.

Let’s see an example:

You can view the codes and experiment with them in Codepen.

First, let’s have two divs with two id’s; “redbox” and “bluebox”.

<div id="redbox" class="box"></div>
<div id="bluebox" class="box"></div>

A generic class “box” has been added to make the styling easy.

Let’s style the divs now:

  position: absolute;
  width: 400px;
  height: 200px;

  background-color: #F00;
  top: 0;
  left: 0;
  z-index: 1;

  background-color: #00F;
  top: 50px;
  left: 50px;
  z-index: -1;

The box class has been positioned as absolute and given some width and height. The id redbox has been given red background color, top and left set to 0 and z-index assigned as 1. The id bluebox has been given blue background color, top and left set to 50px and z-index assigned as -1.

As a result, the redbox comes on top of the bluebox. If we are to change the values of z-indexes as that the bluebox has the z-index value greater than the redbox z-index value, the bluebox comes on top of the redbox. Try it out on the Codepen.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: