You can use the CSS display:table
+ table-caption
solution.
.figure {
display: table;
margin: 0;
}
.figure img {
max-width: 100%;
}
.figcaption {
display: table-caption;
caption-side: bottom;
background: pink;
padding: 10px;
}
<h3>Example of small image</h3>
<figure class="figure">
<img src="https://dummyimage.com/300x100" alt="">
<figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>
<h3>Example of large image</h3>
<figure class="figure">
<img src="https://dummyimage.com/900x100" alt="">
<figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>
In addition, to remove the tiny white space below the image, you can either use:
.figure img { vertical-align: middle; }
or .figure img { display: block; }
Read this answer for more details.