Overlapping elements in CSS
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
Use CSS grid and set all the grid items to be in the same cell.
/* for block elements */
.layered {
display: grid;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
/* or for inline elements */
.inline-layered {
display: inline-grid;
}
.inline-layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
Adding the layered class to an element causes all it's children to be layered on top of each other.
if the layers are not the same size you can set the justify-items
and align-items
properties to set the horizontal and vertical alignment respectively.
Demo:
JsFiddle
.layered {
display: grid;
/* Set horizontal alignment of items in, case they have a different width. */
/* justify-items: start | end | center | stretch (default); */
justify-items: start;
/* Set vertical alignment of items, in case they have a different height. */
/* align-items: start | end | center | stretch (default); */
align-items: start;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
/* for demonstration purposes only */
.layered > * {
outline: 1px solid red;
background-color: rgba(255, 255, 255, 0.4)
}
<div class="layered">
<img src="https://via.placeholder.com/250x100?text=first" />
<p>
2
</p>
<div>
<p>
Third layer
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
</div>
</div>