Adding Captions to Images (CSS)

Written by Tamsin Stone published 9th Mar 2006 | Comment on this article

CSS can be used to add captions below (or above) your images without having to use tables.

Adding Captions to Images

Lets start by adding an image to the page that we want to caption.

<img src="image.jpg" width="220" height="172" alt="Rabbit">

The next step is to wrap this in a div, which will contain the caption and the image. The div is given the class 'rabbitbox' and the image the class 'rabbitimage' so we can style them seperately.

<div class="rabbitbox">
<img src="image.jpg" width="220" height="172" alt="Rabbit" class="rabbitimage">
This is a dwarf lop rabbit called Jasper. He is 6 years old and likes to eat apples.
</div>

The first thing we are going to do is tell the div how wide we want it to be, if we don't specify a width it with stretch across the full page to accomodate the text.
This code goes in the <head> section of your page or in a seperate stylesheet if you have one.

<style type="text/css">
.rabbitbox {width:220px;}
</style>

Already we have the appearance of an image with a caption. The captioned image can be aligned to the left or right with the remaining page text flowing around it or placed on the page with the body text wrapping above and below.
If the image is to have text wrapped around it we'll add a margin on the appropriate side so there is a gap between the image and the text.

To align right add:
.rabbitbox {width:220px;float:right;margin-left:10px;}

To align left add:
.rabbitbox {width:220px;float:left;margin-right:10px;}

To wrap text top and bottom:
.rabbitbox {width:220px;clear:both;}


We can add abit more style to our captioned image, for example, styling the text and adding borders. To style the text add properties to the 'rabbitbox' class. The example below makes the text italic, smaller than the default, aligned right and uses the font family arial.

.rabbitbox {font-style:italic;font-family:arial;font-size:smaller;text-align:right;}

Borders can be added either to the image or the div around both the image and the caption.

To add a border to the image add:
.rabbitimage {border:1px solid black;}

To add a border to the div add:
.rabbitbox {border:1px solid black;}

To add a border to one side:
.rabbitbox {border-right:1px solid black;}

Putting it all together you should end up with something like this...

<style type=text/css>
.rabbitbox {width:220px;width:220px;float:right;margin-left:10px;
font-style:italic;font-family:arial;font-size:smaller;text-align:right;}
.rabbitimage {border:1px solid green;}
</style>