And Finally
And Finally

Reputation: 5704

Constraining a div width to the width of a fluid image inside it

Evening front end wizards. I'm trying to do something that should be quite simple: I want to have images floated right or left in my body content, with a caption below each image. To try and achieve this I'm floating a div with the image inside it, followed by a span with a caption below. I've given the image max-width 100% so my layout is responsive.

Is there any way using just CSS and HTML that I can constrain the width of the containing div to the width of the image inside it? I'm finding that the span below pushes out the width of the div, whether it's display:inline-block or not. I'd like the span to always be the same width as the image, so the text wraps in line with the image's right edge.

I'd like to be able to use images of varying widths, so setting a max-width on the div doesn't really do the trick. I could do it easily enough with JQuery, but that would be cheating.

Any suggestions gratefully received! You can see what I'm talking about at http://jsfiddle.net/andfinally/yBHjK/

Upvotes: 2

Views: 5438

Answers (3)

Scott Obert
Scott Obert

Reputation: 146

It sounds like you want the containing div to expand it's width only for img elements and not span elements. Is that correct?

There is no pure CSS solution for this, JavaScript is the best way to achieve what you're after.

Two similar questions:

Upvotes: 0

Danny S
Danny S

Reputation: 127

You might want to try adding:

style="word-wrap: break-word;"

to the span elememt, or in a css sheet with:

.image span {
    word-wrap: break-word;
}

Edit: This should break the text in your span element to fit across two or more lines instead of stretching out past your image's width.

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

Try setting a max-width to the container and then width: 100% to the image. It should work.

Look http://jsfiddle.net/nMEVd/1/

Upvotes: 2

Related Questions