Is there an easy way with relative positioning to overlay a transparent PNG (or any other image) over an image tag with CSS just by passing a class?
<img class="watermarked" src="http://placehold.it/500x325.jpg" alt="Photo">
Then the CSS might be similar to this (not working):
.watermarked{
background-image: url("http://placehold.it/100x100/09f/fff.png");
position: relative;
left: 30px;
opacity: 0.5;
}
Ideally, I would be able to define the path of my "watermark" overlay image within CSS and then any image that I add "watermarked" class to would get this image overlaid on top with some negative relative positioning. It should be able to be applied to multiple images on a single page, so a single use DIV will not work.
Obviously, this does NOT do anything to protect the underlying image...so to call it a watermark is not really accurate...more of a temporary overlay. I am amazed that an answer is not readily available but I have poked around and not found an answer here or on google.
If you're going for a CSS-only solution, I'd recommend wrapping the image you want to watermark in a container div
, which we can then add an :after
pseudo-element containing our watermark.
The ideal solution would be to apply the :after
pseudo-element directly to the img
element, but unfortunately most browsers don't support using :before
or :after
on img
elements. If so we could have applied the .watermark
directly to the img
tag.
In the solution below we're overlaying an :after
pseudo-element over the entire image, then placing the watermark logo in the top-left corner.
One advantage this solution has is the :after
element covers the entire image, which prevents users from right-clicking and saving the image (though this doesn't prevent anyone with a bit of web experience from finding the image URL to download it). Because the :after
element covers the entire image we could also apply a semi-transparent background to slightly obscure the watermarked image.
So we're left with this solution:
.watermarked {
position: relative;
}
.watermarked:after {
content: "";
display: block;
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
background-image: url("http://placehold.it/100x100/09f/fff.png");
background-size: 100px 100px;
background-position: 30px 30px;
background-repeat: no-repeat;
opacity: 0.7;
}
<div class="watermarked">
<img src="http://placehold.it/500x325.jpg" alt="Photo">
</div>