Advanced Positioning of HTML Elements
The z-index
property allows you to define the stack order of HTML elements.
z-index and Overlapping
z-index
: Defines the "stacking order" of HTML elements. Elements with a higher z-index will appear on top of those with a lower z-index.
If two boxes overlap, the one with the higher z-index will be displayed on top. If z-index values are the same, the element defined later in the code will appear on top.
For example, an element with a z-index of 1 will be below an element with a z-index of 2.
Example of Using z-index
.box1 { position: absolute; z-index: 1; } .box2 { position: absolute; z-index: 2; }
Here, box2
with a z-index of 2 will be positioned above box1
with a z-index of 1.
Using absolute and relative
position: absolute
means the element will have a position relative to its closest positioned ancestor (not static).
For example, a child element using position: absolute
and top: 10px
will be positioned 10px from the top of its parent element.
position: relative
means the element will move relative to its normal position.
<div class="container"> <div class="small-box">Small Box</div> </div>
.container { position: relative; /* Parent element with relative position */ } .small-box { position: absolute; /* Absolute position relative to the parent element */ top: 10px; /* Positioned 10px from the top of the parent element */ left: 20px; /* Positioned 20px from the left of the parent element */ }
In the code above, the div with the class .small-box
is positioned absolutely within the parent div with the class .container
.
Therefore, the .small-box
is positioned 20px to the right and 10px down from the top left corner of the .container
.
Follow the highlighted code steps to try it out.
When the z-index
property is the same, the element defined first will be positioned above the element defined later.
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help