In a responsive design, how can the width of a <figcaption>
be made to adjust according to the width of the <img>
, but not exceed it?
<section>
<figure>
<img src="link.jpg">
<figcaption>Caption</figcaption>
</figure>
</section>
The corresponding CSS only limits the <img>
and not the <figcaption>
, see:
How can the <figcaption>
be constrained along with the <img>
, without using max-width: 200px
(or 12.5em) on the <figure>
container?
Here are the important bits of CSS (full on JSFiddle):
section figure {
position: relative;
margin: 0 auto; /* to center it */
}
section figure img {
max-width: 100%;
vertical-align: middle; /* to make sure images behave like blocks */
}
section figure figcaption {
position: absolute;
right: 0; bottom: 0; left: 0;
}
Setting
max-width: 100%; display: inline-block;
(http://jsfiddle.net/vZpmq/1/) orfloat: [left|right]
(http://jsfiddle.net/cdmU3/1/) on thesection
would cause it to shrink-to-fit it's content (and the box it's in). You might need to rework some other things to fit those changes, though.Alternatively, try setting
width: 100%; height: auto;
on the img, and set the width on thefigure
element? http://jsfiddle.net/9yUsP/(setting
height: auto;
on theimg
means it's retain it's aspect ratio regardless ofheight
orwidth
attributes set on theimg
element itself)