Collected by
Elizabeth Janson

Home Page

Figures & captions

  From www.w3.org/Style/CSS/Buttons/

Figures & captions

Eiffel tower

Scale model of the Eiffel tower in Parc Mini-France

HTML doesn't have an element that allows to insert a figure with a caption. It was once proposed (see HTML3), but never made it into HTML4. Here is one way to simulate such a figure element:

The basic code is
<div>
<img ...>
<p>text</p>
</div>

<div class="figure">
  <p><img src="eiffel.jpg" width="136"
    height="200" alt="Eiffel tower">
  <p class="caption">Scale model of the
    Eiffel tower in Parc Mini-France
</div>

Then in the style sheet you use the classes "figure" and "caption" to format the figure the way you want. For example, to float the figure to the right, in a space equal to 25% of the width of the surrounding paragraphs, these rules will do the trick:

DIV.figure {
  float: right;
  width: 25%;
  border: thin silver solid;
  margin: 0.5em;
  padding: 0.5em;
  text-align: center;
}
P.caption {
  font-style: italic;
  font-size: smaller;
  text-indent: 0;
}

In fact, only the first two declarations (float and width) are essential, the rest is just for decoration.

There is one problem here, and that is that the image may be too wide. In this case, the image is always 136 px wide and the DIV is 25% of the surrounding text. So if you make the window narrower, it may be that the image overflows the DIV (try it!).

If you know the width of all images in the document, you can add a minimum width to the DIV, like this:

DIV.figure {
  min-width: 150px;
}

Another way is to scale the image itself. That's what we have done with the image on the right here. As you can maybe see if you make the window very wide, JPEG images don't scale very well. But if the image is a diagram or a graph in SVG format, scaling in fact works beautifully. Here is the mark-up we used:

St. Tropez

Saint Tropez and its fort in the evening sun

<div class="figure">
  <p><img class="scaled" src="st-tropez.jpg"
    alt="St. Tropez">
  <p class="caption">Saint Tropez and its
    fort in the evening sun
</div>

And this is added to the style sheet, which already contains 'div.figure' and 'p.caption' listed beside the Eiffel Tower notes:

img.scaled {
  width: 100%;
}

The only addition is the last rule: it makes the image as wide as the inside of the DIV (the area inside the border and the padding).

Email
CSS begins here
Back to cursor choices or on to buttons.

This page is part of Elizabeth Janson's web site

http://www.oocities.org/elizatk/index.html

My other sites are the Anglican Parish of Northern Mallee,
Tetbury residents in the Eighteenth Century
my Australian Family History and Barrie, our Family Poet.