CSS Cookbook/Images

From DPWiki
Jump to navigation Jump to search

In-line images—images that sit between paragraphs or above the chapter head—would seem to be basic HTML, the <img /> tag. Complications arise due to standards compliance, and further ones when you want to have a small image (a "thumbnail") act as a link to a larger copy of the same image, and when you want to "float" an image so it sits in the paragraph with text running around it, or bleed it into the margin.

These rules from the Cookbook styles apply to images and are referred-to below.

img { /* the default inline image has */
	border: 1px solid black; /* a thin black line border.. */
	padding: 6px; /* ..spaced a bit out from the graphic */
img.plain { /* image with no border or padding, see float */
	border: none; padding: 0;
p.caption { /* caption para is.. */
	margin-top: 0; /* ..snuggled up to its image */
	font-size: smaller;
	/* font-style: italic;  optional: italic caption */
.center { text-align: center; text-indent:0; }
.center table { margin-left: auto; margin-right: auto;  text-align: left; }
.center img { margin-left: auto; margin-right: auto; }
.figcenter { margin-left: auto; margin-right: auto; } /* guiguts */

In-line Images

Believe it or not, a simple image and its caption are coded as follows:

<div class="center">
   <a id="image03" name="image03"></a>
   <img src="images/image03.jpg"
      alt="The Cathedral from the South-West."
      title="The Cathedral from the South-West." />
   <p class="caption">The Cathedral from the South-West</p>

Wiki rules prevent us demonstrating the above code here, but it renders roughly like this:

CSS Image03.jpg

The Cathedral from the South-West

except that the black border is tight around the picture.

Well, why in the world such complex code for a simple image? Take it piece by piece:

  • The <div class="center"> is used to group the image and the caption, and to center them. (In the good old days, you'd have used <center> instead. Sorry; <center> is "deprecated" by standards bodies. The center class in the Cookbook styles is the officially-approved way of centering images and tables now.)
  • The <a id="image03"...> provides an anchor so you can link to the image from the List of Illustrations or from a text reference; it also could be used in automatic indexing.
  • The caption is coded in <p class="caption">. This should be the identical text that appears in the List of Illustrations. In the CSS definition, margin-top:0; snuggles it up close to the image.
  • The alt="..." repeats the caption text. In a browser that does not support images, or if the user has set the browser preference to not load images, or while the image is loading over a slow connection, the alt= text is displayed where the image would or will appear. This text can also be pronounced audibly in browsers for the visually-impaired reader.
  • OK, why is the identical caption repeated a third time in title="..."? It can be used by automatic indexers (Google and its many cousins), but it has another benefit. Hover your mouse cursor above the example picture above for a few seconds: That's the title= text that pops up when you hover. Nifty, eh?

If you have a lot of images and quail at the thought of writing all this HTML for each one, be aware that it can be generated automatically from the proofers' Illustration: markup using regular expressions, as discussed below

Styling the Image

The Cookbook style gives an image a solid black hairline border spaced out 6 pixels from the image. But does your image need either the border or the padding? A lot depends on how you cropped the image. If the image itself includes a white margin and/or a border, adding a border or white padding with the img tag is pointless. In my opinion it makes the best sense to crop the image file tightly, showing only pictorial data, and to create margins and borders in the HTML. It's a waste of time and bandwidth to download the pixels of margins and borders with every image, when nice ones can be created for every image with a few lines of CSS in the head of the document.

Consult the original book to see what its editor did (but some of what he did might have been a compromise with the limitations of printing technology, for instance having to group all photos in one block of "plates"). Feel free to change the border style or color, or the padding, or to put a border only on images that are clickable links.

The class img.plain has no border or padding. Use it for any graphic that should never have a border or padding around it, for example a small inline logo, or an image that will be floated as described below.

Linked Images

For some books you get only the low-resolution images in the proofing scans, but for some works you get separate, high-quality image scans in large files: a 300dpi scan of a 4x5-in image is 1200x1500 pixels, 1.8 megapixels, a couple of megabytes of data in memory and about 500Kb when saved as a JPEG with minimal compression. If you included even one or two of those in-line, the book would be unusable for many readers. But if you scale them far down, and/or save them at lowest JPEG quality, you are just throwing away data that has historical and literary value—forcing readers for decades to come to peep at the book through a cobwebbed keyhole. What to do?

This has been discussed at length in the forums. One good way to proceed is to make two copies of each image:

  • After cleaning up the original scan as per the Guide to Image Processing, save it in its original dimensions at a JPEG compression that reduces it to 15%-20% of the uncompressed size (e.g. PhotoShop's JPEG quality 8).
This file is named imagennh.jpg. The terminal "h" means hi-resolution. (Feel free to think of a better naming convention, especially one that lets the hi-res and lo-res image names sort out separately in the folder display.)
Sometimes, image processing tools don't produce as well compressed JPEGs as they could do. To work around this, jpegoptim can be used on the resulting JPEG to losslessly compress the image further. This might gain you anything between 1% and 30% file size savings without any change in the image appearance.
  • Make a copy and scale it to 500 pixels or less in its longest dimension, and save at a higher compression level (e.g PhotoShop's quality level 1 or 2).
This file is named imagenn.jpg.
Again, jpegoptim can be used on this JPEG to compress it further.
  • Store all the images in the images folder, which is a PG rule.

Include the smaller image in-line, but enclose it in a link to its larger version. The HTML is:

<div class="center">
   <a id="image03"></a>
   <a href="images/image03h.jpg" >
     <img src="images/image03.jpg"
        alt="The Cathedral from the South-West."
        title="The Cathedral from the South-West." />
   <p class="caption">The Cathedral from the South-West</p>

The difference from the preceding example is that here the <img /> tag is wrapped in a link that points to the larger image. (Generation of this markup is discussed below) The image looks the same as the previous example, but clicking the image opens the high-resolution image03h.jpg.

Wiki rules forbid demonstrating this code here.

Captions as Thumbnails

The Cathedral from the South-West, as seen on a rare sunny day.

A different approach to linked images was used in a widely-admired book, the Illustrated History of Furniture. In this elegant HTML edition, the many large images are stored only at their full resolution, but they are not loaded with the page. Instead the post-proofer encloses the caption in a <div class="image">, the CSS rule for which is:

div.image {
	float:right;	/* floating box on right */
	width:35%;	/* 1/3 of the text column, could be less */
	border:thin dashed #666; /* subtle border */
	background-color: #EEE; /* light shading */
	padding-left: 6px; /* ease text away from border */
	margin-left: 6px; /* ease border away from body text */

It creates a small floating box, coded much like the sidenote boxes discussed here. You choose some key phrase of the caption and mark it up as a link to the image file (<a href="images/image03h.jpg"/>Some key phrase</a>).

Using this technique, a graphics-heavy book loads quickly. The reader chooses which images to download. Because the reader does not have a small image to look at, the caption must be informative enough to tell whether the image is of interest or not.

Floating Images

CSS Image04.jpg

Tomb of an Abbot in South Choir

When an image is small you can consider "floating" it to the side with the text running around it. Only do so if the original work did it. And consider whether they might have done it only to reduce the page-count and hence the cost of the book. There's no need to conserve paper and ink when designing an etext!

When there is a caption separate from the image, as in the example just to the right, you wrap the image and its caption in a <div class="floatr">. You place the code just before the text paragraphs to which it should lie parallel, like this:

<div class="floatr">
	<a id="image35"></a>
	<img class="plain" src="images/image35.jpg"
		alt="Tomb of an Abbot in South Choir"
		title="Tomb of an Abbot in South Choir" />
	<p class="caption">Tomb of an Abbot in South Choir</p>	

If the image contains its own caption, CSS Image05.jpg or doesn't need a caption, then the floated box does not have to contain both an image and a caption paragraph. In that case you can float the image by wrapping it in a <span class="floatr/l"> and place it anywhere within a paragraph. The code is almost the same as before, except that span replaces div. Because it's a span, you can start the image inside a paragraph, not at the top of one.

As you can see, having too many floating images gives the text a choppy, checkerboard quality that is not pleasant to read. Floats need to be used with restraint. They should probably be kept to one side of the page to avoid the slalom effect seen here. While looking at these examples, drag your browser window slowly narrower and then wider, and watch what happens at very wide and very narrow sizes.

The CSS rules for right- and left-floating images in the Cookbook read thus:

.floatr, .figright {
		float: right;
		clear: right;			/* don't allow floats to overlap */
		text-align: center;		/* img & caption centered in box */
		border: 1px solid black;	/* OPTIONAL thin border */
		padding: 3px; /* keep caption text away border */
		margin: 0 0 0 4px; /* left margin to set box out from body */
.floatl, .figleft { /* just like floatr but opposite */
		float: left;
		clear: left;
		text-align: center;
		border: 1px solid black; 
		padding: 3px;
		margin: 0 4px 0 0; /* right margin to set box out from body */

The styling here, including

  • the 1-pixel solid black border,
  • the 3-pixel padding inside the border to separate it from the image,
  • the 4-pixel text-side margin to separate the border from the body text,

are all changeable to better imitate the original book and better suit your tastes. If you eliminate the hairline border you may need to increase the margin to get a better visual separation from the body text.

Coding Height and Width

The <img /> element can be coded with height= and width= properties to specify the size of the image being loaded. I have not supplied these values in the books I have styled, mostly from laziness: it is tedious to get the pixel dimensions of each image and code them into the file.

The worth of adding these values is that the browser reads the HTML text first, before it downloads the images. When it gets the width and height values with the HTML, the browser can lay out the page image correctly at once, before the image files arrive. Without them, it has to lay out the page on the basis of some assumed size. When it finally gets the image file, it discovers that the image is larger or smaller than it assumed, and it has to lay the page out again. The page image jumps around unpleasantly as the browser paints it over and over.

It would be a good idea to code image dimensions into the <img /> tag if it can be done without too much labor. A caution: the browser uses the height and width encoded in the <img /> tag. If the image has a different size, the browser stretches or squeezes it to fit the specified rectangle. A typo in the height or width could make the image look peculiar.

Regex Markup

The moderately complex code of the image markup can be generated semi-automatically using a series of regular-expression "replace all" operations as follows.

Use search to find all the proofers' [Illustration:...] lines. Manually edit each so that it is a single line, not folded, and to insert the filename.type of the image file (e.g. image03.jpg) immediately after the colon, so the markup looks like

[Illustration:image03.jpg The Cathedral from the South-West.]

Apply the following operations. Copy each search string and replace string and paste them into the fields of the Guiguts search dialog.

Div and Anchor

Find an Illustration and enclose it in a centered div with an anchor for the image name.

Search: (\[Illustration:)(image\d+)(\.\w+)( [^]]+])

Replace: <div class="center">\n <a name="$2" id="$2"></a>\n$1$2$3$4\n</div>

Link to Hi-Resolution Image

Find an Illustration and enclose it in a link to the high-resolution image (named with "h" after the filename).

Search: (\[Illustration:)(image\d+)(\.\w+)( [^]]+])

Replace:   <a href="images/$2h$3">\n$1$2$3$4\n  </a>

Image Element

Find an Illustration and replace it with the equivalent <img element, using the caption as both alt and title texts.

Search: (\[Illustration:)(image\d+\.\w+) ([^]]+)]

Replace:     <img src="images/$2"\n    alt="$3"\n    title="$3" />

CSS Cookbook Topics
Intro  • Styles   • Browser Issues   • About   • Reference
Styling  • Basic Text   • Heads   • Lists   • Tables
 • Block Quotes   • TOC and Index   • Images   • Poetry
 • Sidenotes   • Drama   • Footnotes   • Page Numbers