How to make image caption width to match image width?

I'm including a more generic option that does not require table layout. That means you can add more children without worrying about how the table layout will effect them. You can also choose which children will "expand" the container, and which will not.

All it requires is that the outer element is display: inline-block;, position: absolute;, or any other "shrink-to-fit" type of node.

.container {
  display: inline-block;
}

.no-expand {
  box-sizing: border-box;
  width: 0px;
  min-width: 100%;
  
  background: pink;
  padding: 10px;
}
<h3>Example of small image</h3>
<div class="container">
  <img src="//dummyimage.com/300x100" alt="">
  <div class="no-expand">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</div>

<h3>Example of large image</h3>
<div class="container">
  <img src="//dummyimage.com/900x100" alt="">
  <div class="no-expand">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</div>

You can use the CSS display:table + table-caption solution.

.figure {
  display: table;
  margin: 0;
}

.figure img {
  max-width: 100%;
}

.figcaption {
  display: table-caption;
  caption-side: bottom;
  background: pink;
  padding: 10px;
}
<h3>Example of small image</h3>
<figure class="figure">
  <img src="//dummyimage.com/300x100" alt="">
  <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>

<h3>Example of large image</h3>
<figure class="figure">
  <img src="//dummyimage.com/900x100" alt="">
  <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>

In addition, to remove the tiny white space below the image, you can either use:

.figure img { vertical-align: middle; } or .figure img { display: block; }

Read this answer for more details.

Tags:

Html

Css