views:

310

answers:

2

I am trying to position a caption below an image without explicit knowledge of the images' width. I would like the caption to extend to the full image width, but not to stretch the parent elements' witdh and wrap the lines instead.

I would like to avoid using javascript (reading and applying widths to elements) or using max-width:123px as the range of possible widths is big.

The code currently looks something like this, but can be changed freely. The image width is unknown, but restricted to a maximum dimension.

<div style="float:right; width:auto;">  
  <img src="http://" \>
  <div style="clear:right; min-width:100px; max-width:200px; word-wrap:break-word;">
    My caption which can be longer then the image above and should wrap, I do not want to use max-width.
  </div>
</div>

Any suggestions welcome.

A: 

You could set the width of the caption div to some % of the parent.

That is, if the parent is (x)px wide (due to the image inside causing it to be that wide) then the caption box width can be set to some % (width:100%; perhaps).

Jamie Dixon
That would work if the outer div had an explicit width setting. But in this case the width would still be stretched according to the longest element and only afterwards wrapping a eg. 60% would occur.Nevertheless I was surprised seeing it wrap at all when I tried your suggestion.
Martin
+1  A: 

first, get the styles out of the html; those belong in CSS.

then, I think what you can do is set the div's position to "relative", but leave its width to auto and its overflow to "hidden". The hidden setting should force it to be big enough for all its child elements.

The caption, you then set to position:auto, and bottom:0, left:0, width:100%.

That should accomplish what you're looking for.

Paul
I think w/ the `overflow:hidden`, he may not have to style the caption DIV at all.If position is required, he'd want `position:absolute; top:100%; left:0; width:100%`. Bottom:0 would place the caption on top of the IMG.
mrclay
right, depends on where he wants the box to fall and so on.
Paul
Thanks Paul and mrclay. The relative/absolute combination is the key. I still have to try around a bit, overflow:visible seems to work better and some styling things, but my key question is perfectly answered.
Martin