How to make an image with a fixed-width figure caption with cssArticle created: Feb 4, 2008 Article by: Jeremiah Faith
 The caption text for this image does not wrap to the width of the image, creating an unsightly layout for long captions.
For the IzziD website, I wanted to be able to optionally have captions for all of images that I include in these articles. I learned tips on how to create image captions with css from these two excellent tutorials on image captions with css. However, I had the problem that longer caption text would not wrap with the width of the image, which created a wide and unaesthetically pleasing figure caption (see example above).
 The caption text for this image wraps to the width of the image and looks nicer when the image caption is lengthy. Click image for larger The first image caption tutorial mentioned it was possible to use a <table> with a <caption> element inside. Or alternatively set a fixed width for the table that is equal to the width of the image. I wanted to use <div> rather than a table, and I didn't want to have to specify the width each time by hand; if I update the image size, I'd like to have it automatically update the <div> width property in my html.
To dynamically determine the image width and height, I use the Image::Size perl module (a similar function is available in php). So the final perl code to generate a image with a caption that wraps nicely and updates dynamically as the image width changes is:# load module use Image::Size;
# define variables my $image = "image_file.png"; my $larger_image = "large_image_file.png"; my $caption_text = "some caption text that is long"; my ($width, $height) = imgsize($image);
# print html/css print "<div class=image>" . "<a href='$larger_image'><img width=$width height=$height border=0 src='$image'><\/a>". "<div style='width:$width" ."px'>$caption_text". "<BR><i>Click image for larger<\/i>". "<\/div>". "<\/div>"; An example of the html produced by this code for the 202 pixel width thumbnail image on this page is<div class=image> <a href='washington_monument.jpg'> <img width=202 height=152 border=0 src='thumb_washington_monument.png'> </a> <div style='width:202px'>The caption text for this image wraps to the width of the image and looks nicer when the image caption is lengthy. <BR> <i>Click image for larger</i> </div> </div> the font-properties of the caption can be controlled with css using div.image or just .image. I prefer to have the image on the right with a smaller font caption and the article text wrapped around the image: .image { float:right; margin: 5px; clear:right; font-size: 11px; font-family: Verdana, Arial, sans-serif; text-align: left; }
|