if I have an image like so:
<img src="inshot1.jpg" width="100px" height="100px">
and on hover I want that block to be covered in a color. So for example when you hover over it you get a block of red color with the same height and width. So an overlay basically?
Here are two ways you can do this - both involve wrapping the image in a containing element.
Use the Container's Background
You can set the background of the containing element to red and then decrease the images opacity on hover:
The HTML looks like this:
<!-- Uses background color to fade color from behind. -->
<div id="background">
<img src="http://lorempixel.com/100/100/food" height="100" width="100" />
</div>
And the CSS looks like this:
div { position: relative; float: left; }
img { display: block; }
#background { background: red; }
#background:hover img { opacity: 0.5; }
Use a Sibling Element
You can nest an empty span and use it as an absolutely positioned sibling which can serve as the overlay. Check this out - here's the HTML:
<!-- Uses empty span to overlay color. -->
<div id="overlay">
<img src="http://lorempixel.com/100/100/food" height="100" width="100" />
<span></span>
<div>
And the CSS would look like this:
div { position: relative; float: left; }
img { display: block; }
#overlay span {
background: red;
bottom: 0;
display: block;
left: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
z-index: 1;
}
#overlay:hover span { opacity: 0.5; }
You can try out a demo of each solution here:
http://jsfiddle.net/jimjeffers/mG78d/1/
Possible Gotcha
It's important to note that in order for the containing element to match the size of your image you need to do one of four things:
In my jsfiddle example I set the divs to float: left;.
It can be done multiple ways but you can just wrap it in a <div>
with a background-color
and set visibility: hidden
on the image on :hover
div {
background: red;
display: inline-block;
}
img {
display: block;
}
div:hover img {
visibility: hidden;
}
<div>
<img src="https://via.placeholder.com/350x150">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With