CSS Tip - The z-index

26/10/2017
3143

The z-index is probably one of the most misunderstood CSS properties and many developers spend hours trying to get it just right. Once you take a closer look at how this property works, those hours will become seconds.

So let's back up a second before I get too into this. The z index is used to determine the stack of elements within a HTML Document, imagine making your webpage "3D" so to speak. This will only work on elements that have a position property set to either absolute, fixed, or relative.

Those with higher values will appear on top of those with lower or negative values. Consider the following:

<div id="bottom">This div is on the bottom.</div>
<div id="top">This div is on top.</div>

The following CSS would make the div#top appear on top of the div#bottom

#bottom {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
}

#top {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 100;
}

Now the z-index works relative to sibling elements, thus if you have a child element of a div with a z-index higher than its parents sibling (if the parents sibling has a higher z-index than the parent) the child elements will not appear on top of the parents sibling.

Email: