css – How to display an image when leaning on a div?

Question:

I have a div with fixed width and length. The expected would be that when passing over this div, an image with a transition in a defined absolute position is displayed.

I am using only CSS3 and Html. I understand that I need to use the hover property, but I cannot achieve the expected result.

#hoverarea {
  background-color:red;
  width: 100px;
  height: 100px;
}

#machine {
  

}
<div id="hoverarea">

</div>


<div id="machine">

  <img src="http://opensourceecology.org/w/images/3/3a/Metal_Roller.png">

</div>

https://jsfiddle.net/LilNawe/n2f7pnbf/

Answer:

One way to do it using just css:

  • Place the image inside a container div with fixed width (in this case #hoverarea with 100 x 100)
  • Give the image a maximum and minimum width of 100% so that it occupies the size of the container (this is important for the hover effect)
  • Give the image an opacity of 0 so that it is not visible
  • Set in the pseudo-class :hover of the image opacity:1 , in this way when entering the div the image is displayed. How the image and the div are the same size produces the desired effect.
  • By means of transition specify in which property we want to apply the transition and with what duration. In this case the property would be opacity
#hoverarea {
  background-color:red;
  width: 100px;
  height: 100px;
}

img {
  max-width: 100%;
  max-height: 100%;
  opacity: 0;
  transition: opacity 2s;

}

img:hover {
 opacity: 1;  
}
<div id="hoverarea">
<img src="https://www.venturestream.co.uk/wp-content/uploads/2016/09/Square-300x300.jpg">
</div>


  

You can read about transitions here: W3schools – Transitions

In the following link you can see the different transition speed curves W3schools – Transitions speed

For the answer I have used the default value, which is ease and specifies that the beginning of the transition will be slow, then it will increase and end slowly.

Scroll to Top