htmlcssresponsive

How to make watermark responsive?


I'm using this css to add a watermark to my images on my site, the problem is that when it fits on a phone screen the watermark logo looks bigger almost taking up the whole thumbnail I would really appreciate your support

.watermarked {
  position: relative;
}

.watermarked:after {
  content: "";
  display: block;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  background-image: url("https://i.imgur.com/5GQA67n.png");
  background-size: 100px 100px;
  background-position: 30px 30px;
  background-repeat: no-repeat;
  opacity: 0.7;
}
<div class="watermarked">
  <img src="https://i.imgur.com/xDlSplX.jpeg" alt="Photo">
</div>


Solution

  • The .watermarked element should fit the child image's width and height. Set the background-size and background-position using percent, so they would change according to the parent's size:

    .watermarked {
      position: relative;
      width: fit-content;
      height: fit-content;
    }
    
    .watermarked:after {
      content: "";
      display: block;
      position: absolute;
      inset: 0;
      background-image: url("https://i.imgur.com/5GQA67n.png");
      background-size: 20%;
      background-position: 3% 3%;
      background-repeat: no-repeat;
      opacity: 0.7;
    }
    
    img {
      object-fit: cover;
    }
    
    .img1 {
      width: 100px;
      height: 100px;
    }
    
    .img2 {
      width: 300px;
      height: 300px;
    }
    <div class="watermarked">
      <img class="img1" src="https://i.imgur.com/xDlSplX.jpeg" alt="Photo">
    </div>
    
    <div class="watermarked">
      <img class="img2" src="https://i.imgur.com/xDlSplX.jpeg" alt="Photo">
    </div>
    
    <div class="watermarked">
      <img src="https://i.imgur.com/xDlSplX.jpeg" alt="Photo">
    </div>