I have a simple, single page with a single, fixed-width content column (fixed width on body
), that, among other things, contains figures as blocks.
Figures always contain exactly one image, an optional caption, and are styled with a border and a background. It is preferable that images retain their original size, but should be scaled down if the border-box width of the figure would not fit into the column. Captions, if present, should be contained within the figure (i.e. on its background and within its borders), and should be broken to multiple lines if it would cause the figure to grow in width.
I have come across basically two ways of achieving this, but I cannot really get either to work.
The first one is setting display: table
on the figure and display: table-caption
on the caption, but this seems to cause the browser to take it completely out of the figure, not leave it inside.
The second is setting width: min-content; max-width: 100%
on the figure. This works properly if the figure is naturally smaller than the column width, but I could not manage to have it shrink the image. While the figure element itself is correctly width-limited, the image in it simply overflows. (width: fit-content
also takes the caption's width into consideration.) object-fit: scale-down
on the image gets completely ignored. If I set width: 100%
and/or max-width: 100%
, it gets arbitrarily scaled down to match the minimum width of the caption, if present, or 0 if there's no caption. Only thing that truly works is if I specify the image's exact width, but then it loses responsiveness.
I have looked all over the web for a solution, including SO, but not found a proper solution. Here's a simplified HTML/CSS to illustrate what I'm talking about.
<body>
<figure>
<img src="some-image.png" />
<figcaption>Lorem ipsum dolor sit amet, this might be narrower/wider than the image above or completely omitted.</figcaption>
</figure>
</body>
And the CSS:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
border: 1px solid red;
width: 300px;
}
figure {
background: gray;
display: block;
border: 1px solid blue;
width: min-content;
max-width: 100%;
}
figure img {
border: 1px solid green;
object-fit: scale-down; /* Doesn't seem to do anything */
width: 100%; /* This causes the image to shrink to the caption, or 0 if there is no caption */
max-width: 100%; /* Same as above */
}
I think I kind of understand why this is happening, I have no idea how to solve it. Any help would be appreciated. If JavaScript is absolutely necessary, please do not use any other frameworks than JQuery.
Here are two screenshots demonstrating both a correctly working and an overflowing case: