0

I am trying to create a rectangle masking div with variable width and height. An image overlapped with a rectangle div, inside of the rectangle should preview the background image and outside of the div is filled with transparent background color. I have attached an image to clarify my concern.

For example, I have found below code from w3schools. It is created with a circle overlapped masking. In my case masking should be in rectangle and the rectangle size and positions may vary. Please suggest me a better solution!

.mask2 {
  -webkit-mask-image: radial-gradient(circle, black 50%, rgba(0, 0, 0, 0.5) 50%);
  mask-image: radial-gradient(circle, black 50%, rgba(0, 0, 0, 0.5) 50%);
}
<div class="mask2">
  <img src="https://www.w3schools.com/css/img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
vishnu
  • 2,848
  • 3
  • 30
  • 55

1 Answers1

1

Simplest solution would be drawing a rectangle with a large shadow on top:

.mask2 {
  position: relative;
}

.cutout {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 20px;
  left: 30px;
  box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .7);
}
<div class="mask2">
  <div class="cutout"></div>
  <img src="https://www.w3schools.com/css/img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</div>

Idea taken from here.


Alternatively, and this isn't a perfect solution but you could duplicate the image, tune opacity down and put masked-out duplicate on top.

.mask2 {
  position: relative;
  background-color: #000000
}

.mask2 img {
  opacity: 0.3;
}

.mask2 img.masked {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 1;
  clip-path: polygon(30% 30%, 70% 30%, 70% 70%, 30% 70%)
}
<div class="mask2">
  <img src="https://www.w3schools.com/css/img_5terre.jpg" alt="Cinque Terre" width="600" height="400" class="masked">
  <img src="https://www.w3schools.com/css/img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</div>
SnoopFrog
  • 684
  • 1
  • 10