The result of two or more overlapping elements in CSS depends on the specific styles and layout rules applied to the elements. For example:
- If two elements have different values for the
z-index
property, the element with the higher value will be stacked on top of the element with the lower value.
<style>
.element1 {
position: absolute;
z-index: 1;
background-color: red;
width: 200px;
height: 200px;
}
.element2 {
position: absolute;
z-index: 2;
background-color: blue;
width: 200px;
height: 200px;
left: 50px;
top: 50px;
}
</style>
<div class="element1">
</div>
<div class="element2">
</div>
In this example, the blue .element2
is stacked on top of the red .element1
because it has a higher z-index
value.
- If two elements have the same value for the
z-index
property, the order of the elements will be determined by their order in the HTML document.
<style>
.element1 {
position: absolute;
z-index: 1;
background-color: red;
width: 200px;
height: 200px;
}
.element2 {
position: absolute;
z-index: 1;
background-color: blue;
width: 200px;
height: 200px;
left: 50px;
top: 50px;
}
</style>
<div class="element1">
</div>
<div class="element2">
</div>
In this example, the red .element1
is stacked below the blue .element2
because both elements have the same z-index
value, and .element2
appears later in the HTML document.
In addition to the z-index
property, the size, position, and other layout properties of elements can also influence their behavior when they overlap. For example, elements that have a position
property value of absolute
or fixed
can be positioned relative to other elements or the viewport, and the value of the display
property can determine whether an element is a block-level or inline element and how it affects the layout of other elements.