Creating a color transparent overlay text when users hover over the image is simple and obvious to do with CSS only. It is a way to add some interaction to your website.
In our previous post, We have created a transparent background overlay using background-image
but here we will use the <img>
tag to make it work with mouseover.
I will show you a way of creating a simple hover effect when the user hovers over an image and transparent color overly appears.
It will also show the text over the image when hovering over an image. The solution will be done using nothing but CSS.
How to Create Color Overlay on Hover
No need to add too many lines of code. All you have to do to put an image inside a div with a class of .overlayone
.
When you hover the image, the image opacity will change from 0 to 1 to provide the transparent overlay effect.
As for as overlay div, we add another div of a class name .overlayinn
that has the content/text which will show up when to hover an image.
<div class="overlayone"> <img src="image/photo.jpg" alt="overlay"> <div class="overlayinn"> <h2>Ayan <span>Ahmed</span></h2> <p>You are looking rock, Have a good day boss.</p> </div> </div>
CSS for Overlay Text
First of all, we need to set the width and height of the main div class name .overlayone
and set it’s a position to relative.
.overlayone{ width: 480px; height: 320px; display: inline-block; position: relative; }
The overlay div requires the position to be absolute. The width and height should be 100%. Here we will also add background-color
which will be in RGB and will show over the image on hover.
.overlayinn { background-color: rgba(0, 182, 158, 0.7); height: 100%; width: 100%; opacity: 0; top: 0; left: 0; position: absolute; padding: 70px; transition: opacity .5s; }
Image Hover CSS
On the hovering,.overlayone
we only set the opacity 1, but in an active state, we make sure opacity should be 0. Let’s take a look at all CSS:
.overlayinn:hover { opacity: 1; transition: opacity .5s; }
You can customize CSS code of color overlay on hover by changing the background color and set different opacity to create a different effect.
Thanks, this helped me a lot!
I have one question though: I want the image to resize on different screens so I changed the width and height of overlayone to 100%. This seems to work besides that I have a small color-bar at the bottom when I hover (as if the image doesn’t fit in height), but I have both heights & widths (overlayone and overlayinn) at 100%… Any thoughts?
Thanks again!
Hi Marcel Mooij!
Use the CSS media queries to set different image sizes on different media screens.
Interesting, but what if you *only* need a color overlay and NO text.
Thanks for your valuable feedback!
If you need only a color overlay instead of text, don’t place anything inside the
<div class="overlayinn">
tag.