Good day, everyone. Today, we'll talk about an interesting and important topic in CSS: the z-index
and Stacking Context. This concept is indeed very important in web design and understanding it can help in creating advanced and beautiful layouts.
Let's start with z-index
. The z-index
in CSS allows you to control the stacking order of elements in the z-axis. It means you can determine which element will be displayed on top of other elements.
This feature is only applicable to elements that are positioned with absolute
, relative
, fixed
, or sticky
; it can be used. If the positioning of an element is such that it is static
, the z-index
setting will not have any effect on it.
But what is a Stacking Context? A Stacking Context is a collection of elements that exist on the same stacking order and the z-index
only affects them. This context can be established by creating a new position and assigning a specific z-index
to an element, which in turn causes elements to be stacked in that new context.
Let’s illustrate this concept with an example to better explain it.
<style>
.parent {
position: relative;
z-index: 1;
background: lightblue;
padding: 20px;
}
.child {
position: absolute;
z-index: 10;
background: coral;
width: 100px;
height: 100px;
top: 10px;
right: 10px;
}
</style>
<div class="parent">
This is a parent element.
<div class="child">
Child element
</div>
</div>
Now, let’s take a look at this code and analyze what happens here:
<style>
: This tag <style>
is used for defining internal CSS and includes CSS rules related to the layout and positioning of elements.
.parent
: This style is related to the parent element which has a positioning of relative
and a light blue background color.
z-index: 1;
: This z-index
creates a new stacking context for the parent element where other elements stack based on this.
.child
: This style is for the child element which is positioned absolute
and has a different background color.
z-index: 10;
: This z-index
indicates that the child element will overlay on top of other elements within the same newly created stacking context.
By understanding this concept, you can better control the layout of overlapping elements on web pages, which is essential for creating complex and aesthetically pleasing designs.