Tracy Nuwagaba
Tracy's blog

Tracy's blog

Z-index CSS property

Z-index CSS property

Tracy Nuwagaba's photo
Tracy Nuwagaba
ยทJul 17, 2021ยท

2 min read

Subscribe to my newsletter and never miss my upcoming articles

I'm sure you have seen some elements on a website overlap each other. Well, it's the CSS z-index property that controls this. I learned about this a few days ago while working on a personal project.

The z-index property in CSS controls the vertical stacking order of positioned elements that overlap each other. Z-index determines the stack level of an HTML element. The stack level refers to an element's position on the z-axis as opposed to the x-axis and the y-axis.

To use this property, an element should be positioned for example absolute, relative, or fixed positioning. By default, elements have static positioning. This means that when you apply z-index to an element with a static positioning, it won't take effect. It works on elements with a position other than static.

Values

The default value is auto. With auto, the Z-axis order will be determined by the position of the HTML element on the page. The last sibling will appear first as it was defined last. Overlapping elements with a higher z-index cover those with a small one. An element with a higher z-index will be brought closer to the user's eyes.

Z-index only uses integers, it does not allow decimals. It's a best practice to use blocks of values or non-consecutive numbers for elements to allow future alterations for example 5, 10, 100 other than 1, 2, 3, 4 which makes it hard to put any element in between the elements. When you use consecutive numbers like 1, 2, 3, 4, you will need to recalculate the z-index of each element if you want to position another element in the middle which can cause frustration.

A frustrated lady

Example

<!-- Html code -->
<div class="green">1</div>
<div class="blue">2</div>
/* styles */
div {
    color: white;
    width: 100px;
    padding: 10px;
    text-align: center;
    position: absolute;
}

.green {
    background-color: green;
    left: 20px;
    top: 20px;
    z-index: 10;
}

.blue {
    background-color: blue;
    left: 60px;
    top: 60px;
    z-index: 20;
}

Result

Result.png

In the above example, the blue box is in front of the green box because it has a higher z-index value than the green box.

Conclusion.

To use the z-index property, elements should have a position other than static with a z-index value other than auto. I hope this article gives a basic explanation of the z-index in CSS. The next time you have a layout where elements overlap each other, remember to position them and use the z-index property.

Thanks for reading!!

ย 
Share this