Pat David Avatar
ABOUT ARCHIVE
Theme
2 min read

HTML figure and figcaption Fiddling

I was fiddling with some site designs recently where I wanted to use an HTML <figure> tag and to include a <figcaption> with it where the <figcaption> text wouldn’t grow past the width of my image.

This is easily demonstrated with this photo of possibly one of the greatest U.S. authors (at least in the top 3 - probably Hemingway and Washington Irving would round out the list). Mr. Mark Twain:

This is Samuel Langhorne Clemens. Otherwise known as Mark Twain.

The code for this would look like:

<figure>
  <img src='twain.jpg'>
  <figcaption>
    This is Samuel Langhorne Clemens.  Otherwise known as Mark Twain.
  </figcaption>
</figure>

You can see it looks just like my “Don’t do this!” above. The long text goes right past the boundaries of the actual image.

I’d rather the text wrap to the maximum width of the image itself.

It turns out to be pretty simple, simply set the <figure> element to display: table and the <figcaption> to be display: table-caption. Then set the caption-side to top or bottom to taste.

So…

<figure style='display: table'>
  <img src='twain.jpg'>
  <figcaption style='display: table-caption; caption-side: bottom;'>
    This is Samuel Langhorne Clemens.  Otherwise known as Mark Twain.
  </figcaption>
</figure>

Which gets me what I’m looking for:

This is Samuel Langhorne Clemens. Otherwise known as Mark Twain.

It’s important to be careful, as the image width dictates the space for the caption. Small sizes will tend to collapse things and look awkward:

This is Samuel Langhorne Clemens. Otherwise known as Mark Twain.

Although, at that point you can probably skip the image + caption as it gets lost at these sizes but you get the point.

Of course, I’m lazy and using Hugo these days, so I wrote a quick shortcode to handle this for me simpler:

{{< figure src="twain.jpg" caption="This is Samuel Langhorne Clemens.  Otherwise known as Mark Twain." >}}

Filed under: html, figure

Share this on: Twitter | Facebook