I’m trying to do something very simple, but for the life of me cannot figure out how, even though I’m not a CSS novice. All I want is to include a caption underneath a photo that wraps and is confined to the width of the photo. Here’s the code for the image and caption:
<div style="display: inline-block; float: right; width: auto; margin: 0 0 1rem 1rem;">
<img src="photo.jpg" alt="photo">
<div>Long hoto caption lorem ipsum dolor sit amet, sit ne appareat verterem, an semper labores reprehendunt sea ipsum dolor. </div>
</div>
But this is what it produces:
If the caption is longer than the width of the photo, the parent div expands to accommodate the long caption. But what I want to happen is that the caption stay confined to the width of the photo in the parent div and wrap the text accordingly.
The only way this seems possible is to add a specific width to the parent div, but I want this to be dynamic so it works for any size photo which is why I use width:auto
. I also tried defining the display as a table like this:
<div style="display: table; float: right; margin: 0 0 1rem 1rem;">
<div style="display: table-cell;">
<img src="photo.jpg" alt="photo">
<div>Long hoto caption lorem ipsum dolor sit amet, sit ne appareat verterem, an semper labores reprehendunt sea ipsum dolor. </div>
</div>
</div>
But no difference, the caption still stretches the width of the parent div. I also tried using width:fit-content
and width:intrinsic
on the parent div and the caption div, but it doesn’t change anything.
Is there really no way to do this with CSS? I’m a big shocked that something this simple seems impossible.