How to Put color over the image when passing the mouse?

Asked

Viewed 1,149 times

0

Place color over image by hovering mouse?

Normal image:

inserir a descrição da imagem aqui

Image with black color superimposed:

<img></img>

How do you do that?

2 answers

2

This type of effect can be done in several different ways with css and Jquery.

Using only css can do by placing 2 Divs, one inside the other. The first with the image and the second with the black, and making the second change the background color only when doing hover:

.imagem {
  background-image:url(https://image.prntscr.com/image/crKy7Cb9SNG2CY91iJAaNw.png);
  background-size:cover;
  width:250px;
  height:250px;
}

.imagem:hover .filtro{ /*estilo aplicado apenas no hover do div imagem*/
  width:100%;
  height:100%;
  background-color:rgba(0,0,0,0.3);
}
<div class="imagem">
  <div class="filtro"></div>
</div>

Note that the background color was made with rgba to allow to specify directly the opacity, which in the case was 0.2, which is almost transparent.

Another solution still in css is to start already with the right style in div filtro but leaves it hidden with display:none, and just show it with display:block when the hover.

.imagem {
  background-image:url(https://image.prntscr.com/image/crKy7Cb9SNG2CY91iJAaNw.png);
  background-size:cover;
  width:250px;
  height:250px;
}

.filtro{
  width:100%;
  height:100%;
  background-color:rgba(0,0,0,0.3);
  display:none;
}

.imagem:hover .filtro { /*agora apenas mostra o div no hover*/
  display:block;
}
<div class="imagem">
  <div class="filtro"></div>
</div>

This last solution will be more appropriate if you have several styles you want to change when you mouse over.

  • NOOOSA THAT COOL!! I didn’t know about this css feature of hovering over one class and applying in another class, I liked it!! Plus I like to use even Jquery, I implemented for jquery really liked tb;

1

Doing with jquery:

<style>
.imagem {
background-image:url('https://image.prntscr.com/image/crKy7Cb9SNG2CY91iJAaNw.png');

width:250px;
height:250px;

}

.filtro {
display:none;
background-color:black;
opacity:0.4;
width:100%;
height:100%;


}

</style>
</head>
<body>

<div class='imagem'>


<div class='filtro'><div>
</div>


$('.imagem').hover( function() {$('.filtro').fadeIn('fast'); } , function() {$('.filtro').fadeOut('fast');  }    ) ;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.