css z-index – ordering of overlapping elements

CSS z-index property decides the ordering of elements when they overlap. Higher z-index mean it is closer to you and hence with appear accordingly. Few points to note about z-index:

  • The default z-index value is auto. In case there is nothing specified in any parent, it is taken as 0.
  • z-index only works on positioned elements (relative, absolute, fixed). It does not work on position:static elements (which is default value of position).

css-z-index

CSS property z-index

CSS version: CSS 2.1
Value: auto | integer | inherit
Initial: auto
Applies to: positioned elements
Inherited: no

Examle – positive and negative z-index

Here we are shifting second div (position:relative) above (-10px) and its z-index value will decide its ordering.

In the following code, CSS property z-index can be changed to the following values
  • 1
  • -1
<style type="text/css">
div {width: 100px;}
.first {
  background-color: lightgray;
}
.second {
  background-color: lightgreen;
  position:relative;
  top: -20px; left:20px;
  z-index: 1;
}
</style>
<div class="first">
  first div with default z-index value
</div>
<div class="second">
  second div with some z-index
</div>
z-index refresh

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments