post: CSS: Z-Index And Element Position Property

Home

CSS: Z-Index and Position Property

Working With CSS

  

Articles

CSS HTML

Z-Index is a css property that controls the vertical stacking order of elements that overlap. It creates 3d layer effects along the z-axis so one appears as if it is physically closer to you.

Elements can overlap for a variety of reasons, for instance relative positioning has nudged it over something else. Negative margin has pulled the element over another. Absolutely positioned elements overlap each other. All sorts of reasons. It doesn’t work in all cases however, which can be frustrating unless you understand why.

For example, a parent div with some padding. To this is added a heading (h1), paragraph (p) and a div with class overlay. The overlay, relative to the parent div, set to full width and height with a minimal z-index and opacity. The heading and paragraph tags set with a higher z-index to appear on top of the overlay. This ensures correct opacity of the text.


<div id="poster">
  <h1>The Poster Heading</h1>
  <p>The Poster Text</p>
  <div class="overlay"></div>
</div>


#poster { position: relative; padding: 50px; }
#poster h1, #poster p { z-index: 3; color: #fff; }
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)";
  -khtml-opacity: .6;
  -moz-opacity: .6;
  opacity: .6;
  z-index: 2;
}

Here the problem is that the z-index layering isn’t working for the paragraph text but the heading is. Changing z-index properties had no effect.

Checking back up the css chain to the main Hx & P definitions fairly quickly shows the solution. The H1 tags had a position definition set. In this case position: relative. Adding position:relative to required tag in this case the p tag sorts the issue and the paragraph appears above the overlay.


#poster h1, #poster p { position: relative; z-index: 3; color: #fff; }

So the key thinh here to remember is: Z-index only works with positioned elements other than the default ‘static’ value (e.g. position:absolute;, position:relative;, and position:fixed;).

An element is said to be positioned if its position property has a value other than static.
~ Visual Formatting Model of CSS 2.1 Specification

So, if you come across the problem where your z-index layering is going awol check the position of your css elements.

comments powered by Disqus