In a previous post about CSS positioning, we briefly mentioned the z-index
property and its role in controlling the Z-axis positioning of elements. In this article, we will explore the z-index
property further and discuss its usefulness when dealing with overlapping elements.
When multiple elements overlap each other on a web page, it becomes crucial to determine which element should be visible, appearing nearer to the user, and which one(s) should be hidden behind it. This is where the z-index
property comes into play.
The z-index
property takes a numeric value (without decimals) and calculates the order in which elements appear in the Z-axis. The higher the z-index
value, the closer the element is positioned to the user.
By default, the z-index
property is set to auto
, which means that the Z-axis order is determined by the position of the HTML element in the page. In other words, the last sibling element appears first as it is defined last in the code.
It’s important to note that the z-index
property only works when the position
property of an element is set to absolute
, relative
, or fixed
. If an element has the default position: static
, the z-index
property will have no effect on it.
Let’s take a look at an example to better understand how the z-index
property works:
.my-first-div {
position: absolute;
top: 0;
left: 0;
width: 600px;
height: 600px;
z-index: 10;
}
.my-second-div {
position: absolute;
top: 0;
left: 0;
width: 500px;
height: 500px;
z-index: 20;
}
In this example, the element with the class .my-second-div
will be displayed on top, with the element .my-first-div
positioned behind it. The z-index
values of 10 and 20 were used in this case, but you can use any positive or negative numbers. It’s common to choose non-consecutive numbers to allow for easier adjustments and positioning of elements.
In summary, the z-index
property in CSS is a valuable tool for controlling the visibility and positioning of overlapping elements on a web page. By assigning specific z-index
values to elements, you can control their order in the Z-axis and determine which element(s) appear nearer to the user.
Tags: CSS, z-index, element positioning, overlapping elements