I need to place an overlay on top of an image with the same measurements. For this, I’m using an absolutely positioned sibling div
.
I cannot use object-fit: contain
as it would not reduce the dimensions of the img
element itself, causing the overlay to be bigger. Basically, the image’s dimensions drive the entire setup.
Current setup given below..image-portrait
works when viewport aspect ratio > image aspect ratio, and .image-landscape
in other case.
HTML :
<div class="relative">
<img src="./image.jpg" class="image-portrait"/>
<div class="overlay">This is an overlay</div>
</div>
CSS:
.relative {
position: relative;
}
.image-portrait {
height: 100vh;
max-width: 100vw;
}
.image-landscape {
width: 100vw;
max-height: 100vh;
}
.overlay {
position: absolute;
top: 0;
height: 100%;
width: 100%;
background-color: rgb(0,0,0,0.5);
}
Is there a CSS only way to do this without JS ?
3
Answers
With your current code given in the question, you should be able to fix it by adding
width: fit-content
to your.relative
class styling. With that, your.relative
parent container will match the width of its contents. So in this case, since the<img>
is driving the width of the inner contents, the container will match its width, and the overlay will just match the width of the parent container.See more about the
fit-content
value here: https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content.If all you want to do is reduce the brightness of an image, a filter is a neater solution than an overlay.
To know more visit here