Advanced Positioning Between Multiple HTML Elements
The z-index property allows you to define the stacking order of HTML elements.
z-index and Overlapping
z-index: Defines the "stacking order" of HTML elements. An element with a higher z-index number appears on top of an element with a lower z-index.
If two boxes overlap, the box with the higher z-index will appear above the other.
When elements have the same z-index, the element that is 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.
.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.
How to Use Absolute and Relative Positioning
position: absolute allows an element to have an absolute position based on the nearest positioned ancestor, not position: static.
For instance, a child element using position: absolute, top: 10px will be positioned 10px from the top of its parent element.
position: relative moves an element relative to its normal position.
<div class="container">
<div class="small-box">Small Box</div>
</div>
.container {
position: relative; /* Parent element with relative positioning */
}
.small-box {
position: absolute; /* Absolute position relative to the parent */
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 using .small-box is positioned absolutely within the div using .container.
That means the .small-box is placed 20px to the right and 10px down from the top-left corner of the .container.
Follow the emphasized parts of the code with asterisks to practice inputting them.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.