CSS Z-Index



CSS Tutorial  >  Position  >  Z-Index

The z-index property specifies the stack order of an element. In other words, when there is an overlap between two elements, the z-index value determines which one shows up on top. The element with a larger z-index value will appear on top.

The picture below illustrates the z-index concept. The x-axis and the y-axis specify the two dimensions that define the display area. The z-axis the third dimension that connects the display area to the eye. The stacked elements are elements that appear in different positions on the z-axis. In this example, stacked element 1 appears closer to the eye than stacked element 2. You can think of the positions as being defined by an index of the z-axis, hence the name z-index.

Illustration of z-index concept

The allowable values for z-index are:

  • number: specifies the order the element appears in. The element with the largest number will appear at the top. The element with the second largest number will appear just below the top element but above all other elements, and so on.
  • auto: sets the z-index number to that of its parent element.
  • inherit: inherits the z-index number from the parent element.
  • initial: sets the z-index number to the default value.

Note that z-index only works on elements that have one of the following three position declarations: position:relative, position:absolute, and position:fixed. In addition, number must be an integer, and negative numbers are allowed.

For example, say we define two blocks with the following CSS code:

#redblock {
  z-index: 1;
  position: absolute;
  width: 80px;
  height: 100px;
  top: 20px;
  left: 20px;
  border: 1px solid #FFFFFF;
  background-color: #FF0000;
}

#pinkblock {
  z-index: 2;
  position: absolute;
  width: 100px;
  height: 80px;
  top: 50px;
  left: 50px;
  border: 1px solid #FFFFFF;
  background-color: #FF00FF;
}

The following HTML code,

<div id="redblock"></div>
<div id="pinkblock"></div>

renders the following:

As we can see, the pink block, with a z-index value of 2, lies on top of the red block, which has a z-index value of 1.

Next: CSS Text




Copyright © 2016   1keydata.com   All Rights Reserved   Privacy Policy   About   Contact