HTML Element Style How to - Add a caption to an image using pseudo element








Question

We would like to know how to add a caption to an image using pseudo element.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.main_image {<!--from  w  ww .  j a v a  2s .  co m-->
  border: 1px solid blue;
  padding: 10px 10px 40px 10px;
  display: inline-block;
  position: relative;
}

.main_image img {
  vertical-align: top;
}

.main_image:after {
  content: "click image to enlarge";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background-color: beige;
  text-align: center;
}
</style>
</head>
<body>
  <a class="main_image"><img src="http://placehold.it/300x200" /></a>
</body>
</html>

The code above is rendered as follows: