Image caption on hover

by Cam Gould

HTML

<div class="caption">
  <img class="caption-image" src="http://faron.eu/wp-content/uploads/2013/05/Cheese.jpg" />
  <div class="caption-text">Some words about how cheesy it is to use a picture of cheese for this example!</div>
</div>

<div class="caption">
  <img class="caption-image" src="https://top5ofanything.com/uploads/2015/05/Tomatoes.jpg" />
  <div class="caption-text">There's nothing witty to say about a tomato, maybe some you say I say stuff. But honstly I can't think of anything...</div>
</div>

CSS

.caption {
  overflow: hidden;
}
.caption-text {
  color: white;
  padding: 10px;
  background: rgba(0, 0, 0, 0.4);
  transition: transform 400ms ease;
}
.caption-image:hover + .caption-text,
.caption-text:hover {
  transform: translateY(-100%);
}

JavaScript

var captionSel = document.querySelectorAll('.caption');

for (let i = 0; i < captionSel.length; i++) {
  let image = captionSel[i].querySelector(":scope > .caption-image");
  let text = captionSel[i].querySelector(":scope > .caption-text");
  text.style.width = image.clientWidth - 20 + "px";
  captionSel[i].style.height = image.clientHeight + "px";
}