How to Use CSS3’s Z-Index Property

In CSS, the z-index property can be used to specify the order of an element. Traditionally in HTML, elements that appear later on in the code take precedence over the ones that come before them. So for example, if you’ve got a <div> element that comes before a <p> element and the two elements happen to overlap, the <p> element would appear on top of the <div>, because it’s order (or it’s z-index) is higher.

Z-index values can range from 1-10000, and z-index value of an element will change its order accordingly. An element with a value of 200, for example, would be ordered ahead of an element with a z-index of 100, even if the element with the value of 200 comes before the 100 element in the HTML. This property is a really great example of one of the ways that CSS can be used to totally manipulate HTML.

Join us in our newest publication:

Here’s how it would look to use CSS to change the z-index of a p element:

   z-index: 300;

As you can see, it’s pretty straightforward in terms of syntax. Aside from numerical values, other values that this property takes are auto, which sets the z-index to the automatic value that corresponds to the order in which the element appears on the page, initial (sets the value to the default), and inherit (inherits the property value from that of its parent).

One real world example of how/when this property is commonly used is in the execution of sticky headers. Sticky elements are quite trendy as of late, and sticky headers and navigation elements are especially prominent. When you have a sticky header, that means that no matter how far a user scrolls down the page, the header is always stuck to the top of the viewport. Maybe you can see where we’ll need z-index for this.

Based on the natural order of things, headers typically have a lower z-index than almost every other element on a page, because they appear at the very top. So when you have a header fixed to the top of a viewport scrolling past items with higher z-indexes, everything else on the page is going to overlap the header, which isn’t exactly the look we’re going for. This can be easily fixed with z-index. When using z-index for this purpose, I like to assign the header a super high z-index, just to be safe. See below for a code snippet on how to implement this effect:

   z-index: 10000;

Use that simple code snippet on your fixed headers and you’ll be good to go!

Share and Enjoy !

0 0