Can a figcaption be restricted to the width of a responsively sized image?
Old question, but I came across the same issue and was able to come up with a fairly neat solution, inspired by this.
HTML:
<figure>
<img src="http://www.placehold.it/300x150" alt="" />
<figcaption>Make me as long as you like</figcaption>
</figure>
CSS:
figure {
background-color: #fff;
padding: 5px;
font-size: .875em;
display: table;
}
figure img {
display: block;
width: 100%;
}
figcaption {
display: table-caption;
caption-side: bottom;
background: #fff;
padding: 0 5px 5px;
}
This ensures the figcaption
does not exceed the width of the figure
, whilst allowing you to keep max-width
on the image. Works in all good browsers and IE8+.
There's a Firefox bug that prevents max-width
working within elements that are set to display: table
. So, instead of using max-width on the image, setting its width to 100% means this works cross-browser. The figure's width will be whatever the native width of the image is, unless that width is restricted in some other way.
So is it possible to use CSS (2 or 3) to achieve both an image caption wrapped to no wider than the image, and an image no wider than the viewport?
Yes. Just use viewport units on the img
- max-width: 100vw;
instead of % - max-width: 100%;
DEMO
Just for completeness:
There are 2 other techniques to get the text to wrap to the width of the image:
1) Set display: table-caption;
on the figcaption
DEMO
2) Set width: min-content
on the figure