The routine task of adding a caption to an image seems ridiculously simple, but I feel that I still haven’t found the optimal way to do it. I’m going to share what I’ve come up with (for lack of a better solution) - please post with your own practices!
For purposes of this example, we need to float the whole box - image and caption - left, and give it a margin.
HTML:
<div class="imgcaption left" style="width:200px"><!--200px is the width of our image. This restricts the box to the image width so that the caption can't stretch it horizontally.-->
<img src="image.jpg" alt="Image alt text">
<span>Caption of this image</span>
</div>
CSS:
.imgcaption {
border:gray 1px solid;
margin:6px 12px;
}
.imgcaption img {
margin:0; /*my caption-less images have default margins which must be overriden*/
}
.imgcaption span {
display:block;
text-align:center;
font-size:75%;
}
.imgcaption.left {
float:left;
}
I’m particularly unhappy with having to specify a container width inline, but I can’t think of any way to avoid it.
Now it’s your turn