2

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/

And Finally
  • 5,602
  • 14
  • 70
  • 110

3 Answers3

2

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

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

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Thanks elclanrs. This is a neat solution. I also thought of doing it this way - I was hoping there was a way to do it that would keep the natural size of the image, but it seems there isn't. Got the most info through skottt's answer, but I appreciate yours too, so giving it an upscore, thanks! – And Finally Feb 05 '12 at 23:32
0

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.

Danny S
  • 127
  • 1
  • 2
  • 13
  • Thanks Danny, when I first saw your answer I cried "Eureka!", but unfortunately when I try it on my JSFiddle and my original page the span still doesn't break. – And Finally Feb 05 '12 at 23:34
0

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:

Community
  • 1
  • 1
Scott Obert
  • 146
  • 2
  • 9
  • Thanks Skottt, basically I want the caption text to wrap at the width of the image. Cheers for pointing me to those other questions: one of them is talking about exactly the problem I'm trying to solve. It includes this link http://www.cs.tut.fi/~jkorpela/www/captions.html to an excellent outline of the issue. – And Finally Feb 05 '12 at 23:25
  • I did look at that link, but it seems a bit different from what you're trying to do. But let us know if you found something that works. – Scott Obert Feb 05 '12 at 23:43