newsonaut

Turning inner space into outer space

March 31, 2015

Make images and captions stay together at the same width

The caption sticks out to the right and the image is pushed over to the left. That's not good.

I’ve been trying off and on for years to find a way to put captions under the images in newsonaut. It always seemed like it should be easy, but it never was.

The problem is that my pictures move around. They can be at the top, the left or the right. That means the captions have to be able to follow them around and match them in width.

The semantic way of doing it is like this:

<figure>
    <img src="#">
    <figcaption>
        Text for caption.
    </figcaption>
</figure>

But what if, say, the image is floated to the right and the caption goes on longer than its width? The caption will keep going as wide as it needs to to stay on one line, and push the image over to one side. It’s not a pretty sight.

I found the solution at Stack Overflow — a place where every imaginable web-related problem is resolved these days. And it made total sense because, well, we’re dealing with a caption here.

First, you display the figure as a table. HTML tables have the wonderful habit of containing whatever is inside of them — including images and captions. Even so, you have to make sure the caption knows that, so give it a display of table-caption. And where does the caption go? In my case it’s caption-side: bottom.

.fig-pic 	{
	display: table;
	float: right;
	margin: 0;
	}
.figcap-pic 	{
	display: table-caption;
	caption-side: bottom;
	margin: 4px 0 10px 20px;
	}
.pic	{
	margin: 20px 0 10px 20px;
	}

Simple and sensible.