CSS Cookbook, 2nd Edition

Problem

You want to use an image for an initial cap.

Solution

Wrap a span element around the first letter of the first sentence of the first paragraph:

<p><span >O</span>nline, activity of exchanging ideas is sped up. The distribution of messages from the selling of propaganda to the giving away of disinformation takes place at a blindingly fast pace thanks to the state of technology&hellip;</p>

Set the contents inside the span to be hidden:

span.initcap { display: none; }

Then set an image to be used as the initial cap in the background of the paragraph (see Figure 2-12):

p { line-height: 1em; background-image: url(initcap-o.gif); background-repeat: no-repeat; text-indent: 35px; padding-top: 45px; }

Figure 2-12. An image used as an initial cap

Discussion

The first step of this solution is to create an image for use as the initial cap. Once you have created the image, make a note of its width and height. In this example, the image of the letter measures 55x58 pixels (see Figure 2-13).

Figure 2-13. The image of the initial cap

Next, hide the first letter of the HTML text by setting the display property to none. Then put the image in the background of the paragraph, making sure that the image doesn't repeat by setting the value of background-repeat to no-repeat:

background-image: url(initcap-o.gif); background-repeat: no-repeat;

With the measurements already known, set the width of the image as the value for text-indent and the height of the image as the padding for the top of the paragraph (see Figure 2-14):

text-indent: 55px; padding-top: 58px;

Figure 2-14. Adjusting the space for the initial cap

Then change the text-indent and padding-top values so that the initial cap appears to rest on the baseline (refer to Figure 2-12).

Note that users with images turned off aren't able to see the initial cap, especially since the solution doesn't allow for an alt attribute for the image. If you want to use an image but still have an alt attribute show when a user turns off images, use an image to replace the HTML character:

<p><img src="/books/3/27/1/html/2/initcap-o.gif" alt="O" />nline, activity of exchanging ideas is sped up. The distribution of messages from the selling of propaganda to the giving away of disinformation takes place at a blindingly fast pace thanks to the state of technology&hellip;</p>

Note also that while the alt attribute is displayed in this solution, the ability to kern the space between the initial cap and the HTML text is lost. The HTML text begins exactly at the right side of the image and can't be moved closer to the letter being displayed in the graphic itself.

See Also

Recipe 2.8 for setting a simple initial cap.

Категории