I’d like to have objects positioned under some images that need to be overlaid. To make the images overlay I’m positioning them absolutely. But when I do this, all content that needs to go underneath the images ends up at the top of the page. Whatever I try I can’t make the content go underneath.
.container {
position: relative;
}
.container img {
position: absolute;
z-index: -1;
/* make it easy to see .more-page-content */
}
<header>
Header at the top of the page
</header>
<main>
<div class="container">
<img src="https://i.imgur.com/ww9TYQv.jpg" alt="blocks">
<img src="https://i.imgur.com/mqReB3b.png" alt="sample">
</div>
<div class="more-page_content">Text that should be below the images</div>
</main>
<footer>
Footer that should be at the bottom of the page
</footer>
2
Answers
Instead of z-index, try top: 0 like this:
As user DBS said in the comments, the main issue is that since you set
position: absolute
for the<img>
children, they are now out of the flow, and the.container
parent is behaving as if it were empty (there’s nothing occupying any space inside it).You can set a size for your container, make your images fit 100% of the container’s width or height, and use
object-fit: contain
to prevent distortions.I hard-coded pixels to specify a size, but you can choose the best approach based on your layout needs. Just ensure the parent container creates a defined area for the children.
Reading: