​​​​​​​ and when freezi...">

How to add overlay color over image using css

if I have an image:

<img src="inshot1.jpg" width="100px" height="100px">​​​​​​​ 

and when freezing, I want this block to be covered in color. For example, when you hover over it, you get a red block with the same height and width. So, the overlay basically?

+6
source share
2 answers

There are several ways to do this, but you can simply wrap it in a <div> using background-color and set visibility: hidden in the image to :hover

HTML:

 <div><img src="img.jpg"></div> 

CSS

 div { background: red; display: inline-block; } img { display: block; } div:hover img { visibility: hidden; } 
+3
source

Here are two ways to do this - both include wrapping the image in the containing element.

Using container background

You can set the background of the containing element to red, and then reduce the opacity of the images on hover:

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 CSS looks like this:

 div { position: relative; float: left; } img { display: block; } #background { background: red; } #background:hover img { opacity: 0.5; } 

Use Sibling Element

You can enclose an empty space and use it as an absolutely located brother, which can serve as an overlay layer. Check it out - here is 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 CSS will 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 the demo of each solution here:

http://jsfiddle.net/jimjeffers/mG78d/1/

Possible gotcha

It is important to note that in order for the contained element to fit the size of your image, you need to do one of four things:

  • Place the contained item.
  • Absolutely position the containing element.
  • Set the display element: inline-block.
  • Explicitly set the height and width of the containing element according to the size of the image.

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

+11
source

Source: https://habr.com/ru/post/908317/


All Articles