How to show text on image when hovering?

It’s simple. Wrap the image and the “appear on hover” description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.

/* quick reset */
* {
  margin: 0;
  padding: 0;
  border: 0;
}

/* relevant styles */
.img__wrap {
  position: relative;
  height: 200px;
  width: 257px;
}

.img__description {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29, 106, 154, 0.72);
  color: #fff;
  visibility: hidden;
  opacity: 0;

  /* transition effect. not necessary */
  transition: opacity .2s, visibility .2s;
}

.img__wrap:hover .img__description {
  visibility: visible;
  opacity: 1;
}
<div class="img__wrap">
  <img class="img__img" src="http://placehold.it/257x200.jpg" />
  <p class="img__description">This image looks super neat.</p>
</div>

A nice fiddle: https://jsfiddle.net/govdqd8y/

EDIT:

There’s another option if you don’t want to explicitly set the height of the <img> on the wrapping <div>, and that is simply setting the <div>‘s display to inline-block. (Keep in mind, though, that it won’t look good if the image fails to load.)

If you choose this option, you’ll notice that there’ll be a slight spacing between the <img> and the bottom of the wrapping <div>. That’s because of the <img>‘s default vertical-align value of baseline. If you set it to bottom it will disappear.

Here’s a fiddle using this option: https://jsfiddle.net/joplomacedo/5cL31o0g/

Leave a Comment