2

I'm creating CSS for an article-style page. The article is a series of paragraphs wrapped at a fixed width — in the example below, 300px — interspersed with occasional figures. Each figure has an img and a figcaption, and is allowed to be up to 400px wide. Note that the real widths are larger, but I've scaled them down for ease of viewing in the example.

The problem I'm having is that I would like each figcaption to be no wider than the img preceding it, even if the img is narrower than its enclosing 400px-wide figure. When the img is 400px wide or wider, this isn't a problem, because it gets scaled down to 400px wide and the figcaption is also 400px wide, as in Image 1 in the example below. But when the img's inherent width is less than 400px, both the figure and the figcaption remain at 400px and the caption extends past the image's edges, as in Image 2 in the example below.

Things I've tried:

  • Setting display: inline-block on the figure
  • Setting width: fit-content on the figure
  • Setting width: calc(foo) on the figure, but I'm not sure what to put in foo

It seems like what I want is for the figure to "shrink-to-fit" the image size, but I understand that's not really a well-supported concept in the CSS model. There must be another way to do this that I don't grok.

Related questions

  • This question, which seems pretty similar, suggests using display: inline-table, which seems like the wrong tool for the job. But perhaps it isn't?
  • This question suggests using display: table as well, though there's also an odd width: 1% which also seems questionable.

p {
  max-width: 300px;
  margin-left: auto;
  margin-right: auto;
}

figure {
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

figure>img {
  max-width: 100%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<p>This is the first paragraph of an article. This is the first paragraph of an article. This is the first paragraph of an article.</p>

<figure>
  <img src="https://placekitten.com/500/300" />
  <figcaption>
    Image 1: This image is wider than the figure max-width of 400px, so it occupies the figure's full width, and its long caption is limited to the width of the image.
  </figcaption>
</figure>

<p>This is the second paragraph of an article. This is the second paragraph of an article. This is the second paragraph of an article. </p>

<figure>
  <img src="https://placekitten.com/350/300" />
  <figcaption>
    Image 2: This image is narrower than the figure max-width of 400px, so it occupies less than the figure's full width, and its long caption is wider than the image. <b>This is the problematic case.</b>
  </figcaption>
</figure>
ravron
  • 11,014
  • 2
  • 39
  • 66

0 Answers0