How to make responsive images and captions get along?
Solution 1
To bind the figcaption
to the width of the img
you'll need to wrap the both of them inside of an element that will collapse to the width of the img
, in this case I've used a div
:
<figure>
<div>
<img src="http://www.phibetaiota.net/wp-content/uploads/2012/10/Google-Data-Center.jpg">
<figcaption>First example caption</figcaption>
</div>
</figure>
With the CSS:
section figure div {
position: relative;
display: inline-block;
max-width: 100%;
padding: 0;
}
You may wish to adjust the overflow
properties of this div
and, obviously, adjust to taste. But if you want to keep the figure
elements as 100% width then you need another element to contain the img
and figcaption
in order to constrain the width of the figcaption
to that of the img
.
Solution 2
I'm not sure if I completely understood what you want to achieve, but is this what you are looking for? http://jsfiddle.net/XjthT/124/
I added a span around the img and caption:
section figure span{
display: inline-block;
position: relative;
}
Comments
-
Baumr almost 2 years
In this scenario, images are living up to responsive design, but the captions are not adjusting along with them.
Makes sense in the code, but how can it be done without setting a
max-width
in pixel values?There are are two images in a single
section
, each inside afigure
with afigcaption
:<section> <figure> <img src="link.jpg"> <figcaption>Caption</figcaption> </figure> <figure> <img src="link.png"> <figcaption>Caption</figcaption> </figure> </section>
In the CSS, we have set a few things, but most importantly, the
img
havemax-width: 100%
set, but there seems to be no way to make the captions do the same:How can this overlap be avoided in a responsive design with older browsers in mind? Apart from setting
max-width: 300px
on thefigure
orsection
elements.Note that any solution should consider that when the window is made smaller, it should allow the image to get smaller:
In other words, the
auto margins
should be go away. (Horizontal margins would waste space on narrow viewports.)