Black transparent overlay on image hover with only CSS?
I’m trying to add a transparent black overlay to an image whenever the mouse is hovering over the image with only CSS. Is this possible? I tried this:
But I can’t get the div to show up.
I’d suggest using a pseudo element in place of the overlay element. Because pseudo elements can’t be added on enclosed
img elements, you would still need to wrap the
img element though.
As for the CSS, set optional dimensions on the
.image element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It’s just worth noting that the dimensions must be on the parent element as opposed to the
img element itself, see.
Give the child
img element a width of
100% of the parent and add
vertical-align:top to fix the default baseline alignment issues.
As for the pseudo element, set a content value and absolutely position it relative to the
.image element. A width/height of
100% will ensure that this works with varying
img dimensions. If you want to transition the element, set an opacity of
0 and add the transition properties/values.
Use an opacity of
1 when hovering over the pseudo element in order to facilitate the transition:
If you want to add text on hover:
For the simplest approach, just add the text as the pseudo element’s
That should work in most instances; however, if you have more than one
img element, you might not want the same text to appear on hover. You could therefore set the text in a
data-* attribute and therefore have unique text for every
content value of
attr(data-content), the pseudo element adds the text from the
You can add some styling and do something like this:
In the above example, the
:after pseudo element serves as the black overlay, while the
:before pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.