How to make responsive images and captions get along?

11,447

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;
}

JS Fiddle demo.

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;
}
Share:
11,447
Baumr
Author by

Baumr

I'm all about (misspelling) hmtl.

Updated on June 04, 2022

Comments

  • Baumr
    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 a figure with a figcaption:

    <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 have max-width: 100% set, but there seems to be no way to make the captions do the same:

    enter image description here

    How can this overlap be avoided in a responsive design with older browsers in mind? Apart from setting max-width: 300px on the figure or section elements.


    Note that any solution should consider that when the window is made smaller, it should allow the image to get smaller:

    enter image description here

    In other words, the auto margins should be go away. (Horizontal margins would waste space on narrow viewports.)