Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add an overlaying color over an image with css

Tags:

css

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?

like image 601
aurel Avatar asked Feb 13 '12 08:02

aurel


2 Answers

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:

  1. Float the containing element.
  2. Absolutely position the containing element.
  3. Set the containing element to display: inline-block.
  4. Explicitly set the height and width of the containing element to match the image's dimensions.

In my jsfiddle example I set the divs to float: left;.

like image 139
Jim Jeffers Avatar answered Nov 14 '22 23:11

Jim Jeffers


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>
like image 43
elclanrs Avatar answered Nov 14 '22 21:11

elclanrs