CSS Layout 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 {<!--   w w w . jav a  2s.  co  m-->
  border: 1px solid blue;
  padding: 10px 10px 0 10px;
  display: inline-block;
  position: relative;
}

.main_image img {
  vertical-align: top;
}

.main_image:after {
  content: "click image to enlarge";
  display: block;
  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: