skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. If all you want to do is reduce the brightness of an image, a filter is a neater solution than an overlay.

    body {
      margin: 0;
    }
    
    img {
      width: 100%;
      filter: brightness(50%);
    }
    <img src="https://picsum.photos/1000/250"/>
    Login or Signup to reply.
  3. Use the aspect-ratio property in responsive layouts where elements
    often vary in size and you want to preserve the ratio between width
    and height.

    img {
      aspect-ratio: 3 / 2;
    }
    

    To know more visit here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search