1

On an image upload page I have a preview of the image. I would like create an overlay that shows the image in a rectangle in the middle, with an opaque overlay around the outside of the rectangle.

Similar to this:

enter image description here

I am able to create a div overlay, but I need to reverse the opaque black background to be on the rest of the image but not on the rectangle. This way I can preview to the user what the final product will look like.

Here's what I have:

.wrapper {
  position: relative;
  height: fit-content;
  width: fit-content;
  display: flex;
}

.overlay {
  max-width: 100%;
  height: 100%;
  aspect-ratio: 1 / 1.42;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  left: 150px;
  border-radius: 0.5rem;
}
<div class="wrapper">
  <img src="https://picsum.photos/500/300"/>
  <div class="overlay"></div>
</div>

Requirements

  1. I need to keep the aspect-ratio and relative size of the rectangle consistent.
  2. No magic numbers or fixed width/height unless dynamically calculated per image, these images will be any size or dimensions and the layout needs to be responsive to (nearly) any screen size.
  3. I can't change the markup too much because I'm working with the drag and drop api to move the rectangle within the image wrapper by changing its left and top positions.
  4. I would like to use CSS or Javascript to solve this, not more HTML
  5. Not looking to use object-fit: cover as I need the entire image visible in its native dimensions.
PsiKai
  • 1,803
  • 1
  • 5
  • 19
  • I think you can use clip path, here is an [example](https://stackoverflow.com/questions/20242806/hole-in-overlay-with-css) ok something like [this](https://medium.com/@wteja/css3-trick-to-create-hole-on-html-element-b288b4db37a4) – Sfili_81 Mar 11 '22 at 07:59

1 Answers1

2

I hope the below code meets your requirements and solves your problem.

.wrapper {
  position: relative;
  height: fit-content;
  width: fit-content;
  display: flex;
}

.overlay {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 0.5rem;
  width: 100%;
  overflow: hidden;
}
.overlay:before{
    position: absolute;
    content: '';
    aspect-ratio: 1 / 1.42;
    height: 100%;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    box-shadow: 0px 0px 0px 145px rgba(0, 0, 0, 0.4);
  
}
<div class="wrapper">
  <img src="https://picsum.photos/500/300"/>
  <div class="overlay"></div>
</div>
Nikesh Kp
  • 374
  • 1
  • 7
  • Thank you, that will work. But honestly I didn't need the pseudo element. I just put the box shadow directly on the overlay. I'll give you the answer since the box-shadow is a good idea. – PsiKai Mar 11 '22 at 14:02