Stylin' Fonts and Text in CSS
Date: Nov 3, 2006
Much of Web design is dealing with type—in paragraphs, headlines, lists, menus, and forms. As a result, the properties in this chapter are essential to making the difference between a site that looks thrown together and one that looks like it has the professional touch. More than any other factor, type makes the clearest visual statement about the quality of your site's offerings. Graphics are the icing on the cake; typography is where good design begins.
If the chapter title has you wondering "Aren't fonts and text the same thing?" the answer is No, and here's why.
Fonts are the different kinds of typefaces. Each font is a set of letters, numbers, and symbols with a unique visual appearance. All fonts belong to large collections, which describe their general look, such as serif, sans-serif, or monospace. Font collections are made up of families, such as Times and Helvetica. A font family in turn can be broken down into font faces, which are variations on the basic family, such as Times Roman, Times Bold, Helvetica Condensed, Bodoni Italic, and so on.
Text simply describes a block of type, like this sentence or the heading of a chapter, regardless of the font in which it is set.
CSS has a set of properties relating to fonts and a set of properties relating to text. Font properties relate to the size and appearance of collections of type. What is its family (Times or Helvetica, for example)? What size is it? Is it bold or italic? Text properties relate to the font's treatment—setting its line height and letter spacing, underlining, and so on.
Here's a way I think about this perhaps seemingly subtle distinction. You can apply font styles, such as bold and italic, to a single character, but text properties, such as line height and text indent, only make sense in the context of a block of text such as a headline or a paragraph.
Let's start with fonts.
Specifying Fonts in CSS
In this section, you'll learn how to use CSS to specify fonts. You can use any length units, both absolute and relative, to specify font sizes, but for reasons discussed throughout this chapter, it's best to use a relative measurement such as ems, so the user can easily scale the type to other sizes.
Introducing Font Collections
Figure 3.1 Serif fonts have noticeable details at the ends of the character strokes. Sans-serif fonts do not have these details.
Example: body {font-family: sans-serif;}
Values: serif, sans-serif, monospace, fantasy, cursive
The simplest way to specify fonts in CSS is by using the five generic collection names—serif, sans-serif, monospace, fantasy, and cursive. These generic names cause the user agent (browser, PDA, cell phone, and so on) to serve up one of these font types. Generic collection names represent the lowest level of support for font styling, and as you will see in a moment, CSS offers some better options than these:
Serif fonts are so named because of the little details, known as serifs, at the ends of the character strokes. These are particularly noticeable in the uppercase letters. Examples of serif fonts include Times, Bodoni, and Garamond.
Sans-serif fonts do not have any details at the ends of the character strokes. They have a more plain appearance than serif fonts. Examples of sans-serif fonts include Helvetica, Ariel, and Verdana.
Monospace fonts such as Courier and Monotype give equal spacing to every letter ("i" has the same amount of space as "m") and are typically used for code blocks in computer related books (this book is no exception), or to simulate the look of a typewriter, whatever that is.
Cursive fonts look like cursive handwriting, although much neater than my own. Examples include Park Lane and Brush Script. Cursive is ideal for wedding invitations and therefore really doesn't get used much on the Web. If you use it, check it in various browsers, because every browser seems to use a different font for cursive.
Fantasy fonts are ones that don't fit in the other categories. The main fantasy here is the hope that this might be a useful way to specify a font. It's almost impossible to predict what font might be served up as a fantasy font from browser to browser, and, therefore, it's best if you avoid fantasy fonts. Also, "fantasy" isn't really an accepted font collection name in the way that cursive and serif are; I have only seen this used as a collection name in CSS, but perhaps I don't get out enough.
If you want to specify a generic font, you write a declaration like this
body {font-family:sans-serif;}
In this case, the browser dishes up Helvetica or Arial or whatever sans-serif font is set as its default and is also on the viewer's computer ( Figures 3.2–3.5 ). It's the most basic way to specify a font. But you can be more specific and declare a font family by name; usually that's what you want to do.
Figure 3.2 Generic font families as displayed by Firefox for Windows.
Figure 3.5 Generic font families as displayed by Safari. Note Safari uses regular fonts for Fantasy and Cursive in headings.
Figure 3.3 Generic font families as displayed by Internet Explorer for Mac OS X.
Figure 3.4 Generic font families as displayed by Internet Explorer for Windows.
Exploring Font Families
In the world of print, you can use just about any font family you want; you purchase and install the font on your computer if it's not already there, and you use it in the design of your document. When your design is complete, you then send the font to the printer along with the document, or you PDF your document so the fonts are converted to vectors (outlines), and you're done. In print, you can work with any of the thousands of available fonts because you have control over them all the way to the printing press.
On the Web, you simply don't have this freedom of choice as far as fonts are concerned. This is one of the most disappointing aspects of the Web for transitioning print designers; you must trust that the viewers have the fonts in which you want your document to be displayed installed on their computers. Fonts aren't part of the browser; they are served up for the all applications on a computer from the system software where they reside. Furthermore, it is impossible to know what flavor of any given font (Times, Times Regular, or Times Roman, for example) a user might have on their machine.
As much as you might want your Web pages' headlines to be displayed in Univers 87 Oblique, the odds of a user having that particular font are, to quote Elvis (Costello), less than zero. In fact, there is only a very short list of fonts that you can be sure users of both Windows and Macintosh have installed on their systems: Times, Arial, Verdana, and Courier.
Even Helvetica, perhaps the most popular sans-serif font of all time, is not included with Windows, but Windows has its own almost identical font, Arial.
"What about automatically downloading fonts as needed from my server to the user?" you ask (you did ask, right?). Good question. Although CSS 3 specifies a way you can request a font from your server in which to display the document, browsers do not currently support this capability. But it is nice to think about, and one day it may be a reality. (Even then, the browser will never install the font on the user's computer but merely use it to display the page).
Until the happy day when fonts are available on demand, to use specific fonts with CSS, you need to list the fonts, in order of preference, in which you would like the document to be displayed. This list must only be by family name—by that I mean you must use Helvetica or Times, not Helvetica Condensed or Times Expanded.
It is accepted practice to write a CSS declaration specifying a of either serif or sans-serif fonts starting with the one you prefer first and ending with a generic font name such as serif or sans-serif like this (in this case, I'm working with sans-serif fonts)
font-family {"trebuchet ms", helvetica, arial, sans-serif}
Because Trebuchet MS is more than one word, it has to be in quotes. If you do this in an inline style that's already inside double quotes, use single quotes on the name, like this
<p style="font-family:'trebuchet ms', helvetica, arial, sans-serif">
or like this in the case of serif fonts
font-family: {charcoal, times, serif}
In the first example using the font-family property above I am saying to the browser, "Display this document in Trebuchet MS, and if you don't have it, use Helvetica. If you don't have either of those, use Arial, and if all else fails, use whatever generic sans-serif font you do have. It is very important to make the last item of a font-family declaration a generic declaration of either serif or sans-serif as a final fallback. This ensures that, at a minimum, your document at least displays in the right type (no pun intended) of font.
In the second example using the font-family property, I first declare Charcoal, a font only available on Macintosh, because I want Macintosh users to have the pleasure of viewing my document in that lovely font. However, because Windows users don't usually have Charcoal, they see the document displayed in the second choice, Times.
Using Embedded Styles (for Now)
To keep things simple, I'm going to show you how to write your CSS styles in a style element in the head of the document. I'll also show you how to remove the link to the external style sheet for now. Doing this means that you won't have to manage a separate style sheet, but the styles that you write will only be available to this one document. That's ideal for developing the layout of a specific page; later you'll create a separate style sheet that can supply styles to multiple pages. Review the start of Chapter 2 if this doesn't make complete sense.
Let's use the HTML document you created in Chapter 1 and modify it to include the style element in the document head, as illustrated by the highlighted code
<head> <title>A Sample XHTML Document</title> <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Language" content="en-us" /> <style type="text/css"> <-- a </style> </head>
The blank line between the opening and closing tag of the style element is where you add your CSS. When the browser encounters the opening tag of the style element, it stops interpreting the code as XHTML and starts interpreting it as CSS. When it encounters the closing tag of the style element, the browser reverts to treating the code as XHTML again. So anything you write within the style element must be in CSS syntax, the same syntax you use if the CSS is in a separate style sheet. This means any code within the style element is formatted like this:
selector {property1:value; property2:value; etc.}
You need to be aware of whether you are writing CSS or XHTML at any given moment during the development of your projects and make sure you format your code accordingly. In the case of the sample XHTML documents I provide at my Web site, www.bbd.com/stylin, the XHTML is already written, so once you add the style element using XHTML, you are working entirely in CSS.
Setting the Font Family for the Entire Page
To set the font family for the entire page, you first need to set it for the body of the document
<style type="text/css"> body {font-family: verdana, arial, sans-serif;} </style>
Save your changes, flip to the browser, and refresh the page. What you see should look like Figure 3.6 .
Figure 3.6 Setting the font-family property of the body element affects the whole document.
Because font-family is an inherited property, its value is passed to all its descendants, which, since body is the top-level element, are all the other elements in the markup. So with one line, you've made it so everything is in the desired font; bathe for a moment in that glow of CSS magic. OK, moving right along . . .
Sizing Fonts
You can use three types of values to size fonts. They are absolute (for example, pixels or inches), relative (for example, percentages or ems), and what I call the sweatshirt keywords (for example, x-small, small, large, and xx-large, among others). All three methods have advantages and disadvantages. Jeffrey Zeldman and other CCS mavens advocate keywords as the least problematic of the three (see A List Apart at www.alistapart.com/articles/sizematters/); but because the keyword method requires some sophisticated CSS to make fonts display at consistent sizes in all browsers and only offers a limited number of font sizes, here, I'm going to have you set font sizes in ems.
Ems can be a strange, confusing unit at first, but they are simply a proportional value—think of them as decimal percentages where .9 em is the same as 90 percent of the baseline size.
Most browsers have a default size for 1 em (approximately 16 pixels high), and if you set an element to 1 em, it takes on that baseline size. If you want a piece of type to be three-quarters of that size, set it to .75 ems, if you want it to be half, set it to .5ems.
When working with ems, you should start by setting the body font-size value to 100 percent (which it is by default, but you should explicitly state it so that you can tweak overall sizes later; you also do this for the benefit of Internet Explorer, as I'll explain momentarily), and then you can set all other sizes in proportion to it. Here's how this works.
First, modify the body selector to look like this
<style type="text/css"> body {font-family: verdana, arial, sans-serif; font-size:100%;} </style>
Although this doesn't produce a visible effect, you now have a tweakable baseline size. The reason you are using a percentage to set the baseline size is because if Internet Explorer sees a baseline size in ems, it overscales—that is, it scales ems in descendant selectors more than it should, both larger and smaller, when the user changes the text size. If the baseline size is set as a percentage, the correct proportions are maintained.
You might notice that the default sizes for common markup elements such as < h1 > through < h6>, <p>, <ul>, and < li > are rather (read "very") large, and if you need to get any amount of content on the page, using these default sizes means the user must do lots of scrolling. Long hours behind market research mirrors have taught me that scrolling is one of the least loved aspects of Web browsing. Also, I simply find that these large default sizes give the page a horsey, poorly designed look.
But, when working in proportional ems, you can choose to make the overall font size a little smaller, because those users who want large text sizes can get them easily by selecting View > Text Size from the browser menu and choosing Larger (or similar, depending on the browser).
Let's say you decide that the new baseline size is going to be 12 points (from a visual standpoint, that is; you will use percents and ems to actually specify the sizes). You set the body font size to 76 percent. Now text in a paragraph is 76 percent of the browser's 16-point default size for paragraphs: 12 points.
Now, when you style the elements 1em equals 12 points, .75 equals 9pts and so on.
Some developers style the html tag (yes, you can do that) to 125 percent (20 points) and style its immediate child body to 50%. This results in all the descendants tags seeing 1em=10 points, so .9em equals 9 points, 1.2ems equals 12 points and so on which gives a very nice correlation of ems in the style sheet to points on the screen.
Remember, regardless of what units you use to style type, the browser has to convert them into pixels, because that's what the screen uses. Every browser has a slightly different algorithm to perform that calculation, so the rounder the numbers the browser uses in the calculations, the more consistent the result from browser to browser. The importance of pixel-accurate type between browsers is a personal matter, but these are a couple of ways you can approach the issue of setting a baseline size for your type.
The bottom line is that if you are using a proportional value method (for example, ems) to size the fonts for the individual selectors, you are then able provide the majority of viewers with font sizes that are more aesthetically pleasing, that result in less scrolling, and that still give visually impaired users the option to override your font size decisions and increase the size of all type proportionally.
In the following examples, you work with the default of 100%, and later, when you start building sites, you can adjust this baseline value to suit the needs of each design.
From the 100% font-size baseline, let's set font sizes on each of the elements using ems, starting with the line under the logo that reads "a New Riders book . . ." ( Figure 3.7 ). We do it this way because setting the baseline at 100% provides more consistent results across browsers than using 1em. However, we use ems for the elements because ems are a familiar and conventional unit for setting type.
Figure 3.7 Here's the original version of the header from the Chapter 1 example with default font styling.
This line is an h3 element, so you're going to set it to .8em (I chose this number because I've done this before and I know that's a nice size for it). Here's what you write
<style type="text/css"> body {font-family: verdana, arial, sans-serif; font-size:100%;} h3 {font-size:.8em} </style>
Figure 3.8 shows how this looks.
Figure 3.8 The "a New Riders book . . ." headline is now a much more appropriate size.
You can see that the headline is now much smaller. (You may be interested to know that by experimentation, I discovered its default size was equal to 1.2ems, or 16 x 1.2 = 19.2 points).
Let's now go on and set the font sizes for other elements in your markup, as follows
<style type="text/css"> body {font-family: verdana, arial, sans-serif; font-size:100%;} h1 {font-size:.1em} h3 {font-size:.8em} p {font-size:.8em} ol {font-size:.75em} ul {font-size:.75em} a {font-size:.7em} </style>
This results in Figure 3.9 .
Figure 3.9 Here the font size for the various elements is set in ems, but the combination of ems and nested tags is making the text in the second list very small.
A couple of points (no pun intended) about these styles: first, you didn't set a style for the list item (li) elements of the two lists, but you did for the ordered list (ol) and unordered list (ul) elements that respectively contain them. If you styled the li element, both lists would display in the same size, but because you styled the ol and ul elements instead, the li elements inherit their values, and you can later make the lists' items different sizes if you wish.
Inherited Styles in Nested Tags
Secondly, although you are already making a nice improvement to the unstyled layout with which you started, the font size for the bulleted unordered list (ul) is very small, even though it's set to the same size as the ordered list (ol).
This problem is caused by the fact that the ol element is set to .75 ems and the a elements nested down inside are set to .7ems. The net result is type in those a elements end up sized to .525ems (.7 x .75). Inheritance of font sizes can work for you, and, as here, against you. Fortunately, the fix here is easy; you simply set a contextual selector for this specific situation, like this
<style type="text/css"> body {font-family: verdana, arial, sans-serif; font-size:1em;} h1 {font-size:.1em} h3 {font-size:.8em} p {font-size:.8em} ol {font-size:.75em} ul {font-size:.75em} ul a {font-size:inherit} a {font-size:.7em} </style>
You simply used the inherit value to tell the a element to get its font size from its containing element. Not only does this ensure that the a element displays in the desired size, but also, if you later want to change the size of the list items, you can just update the ol selector and the nested a element dutifully inherits the new size, and the problem is fixed ( Figure 3.10 ).
Figure 3.10 Now that the inherited sizing issue is .xed, the list is muchmore readable.
You can now test the scalability of your ems-based layout:
- Select View > Text Size > Largest in the browser menu (this is the path in Internet Explorer—it will vary slightly in other browsers). Note that everything scales up nicely for viewers who are visually impaired.
- Vary the value of font-size property of the body selector—try 80 percent and 120 percent, for example. Save and reload the page. Again, all the elements size proportionally. Those of you who have spent hours changing the size attribute of hundreds of font tags in dozens of pages after it's decided that the type sizes are all too big or too small will appreciate the power and convenience of this capability. Next time the client makes some comment like "The problem with you designers is you always make the type so bloody small", you can quadruple the font size of the entire site in about five seconds, and then politely say "Is that big enough for you?"
Let's move on to some other font-related CSS.
Font Properties
The relationship of font sizes is key to indicating the hierarchy of the text in your document. This is achieved through an understanding of the various font properties and an understanding of how font properties can be inherited through the hierarchy of your document. Let's take at the font properties now.
Font-Style Property
Example: h2 {font-style:italic}
Other values: normal, oblique
Font style determines whether a font is italicized or not. It's that simple. If you want a piece of text to be italicized, you write this
p {font-style:italic;}
You can also write oblique instead of italic, but generally, the result is the same. The difference between the two is that, supposedly, italic is simply a distortion applied to the regular font to make it lean to the right, whereas an oblique font is actually designed as a font in its own right and therefore, the theory goes, is more pure. These niceties are pretty much lost on the Web, where a font variation such as Helvetica Oblique can't be specified even though if exists as a font on the user's machine,, and oblique doesn't even alter the regular type in older browsers such as Netscape 4.7.
So, there are only two useful settings for the font-style property: italic to make regular text italicized, and normal to make a section within italicized type regular "upright" text. In this example,
p {font-style:italic;} span{font-style:normal} <p>This is italicized type with <span>a piece of non-italic text</span> in the middle.</p>
the code produces the result in Figure 3.11 .
Figure 3.11 The normal value for the font-style property causes a specified section of type to appear normal within a bit of italicized text.
Font-Weight Property
Example: a {font-weight:bold}
Possible values: 100, 200, and so on to 900, or bold, bolder, lighter, normal
The W3C recommendations for implementing this property simply state that each successive higher value (whether numerical or "weight" values) must produce boldness equal to or heavier than the previous lower value.
bold and bolder give two weights of boldness. lighter allows you to go one step in the other direction if you want a section within bold type to be, well, lighter.
Figure 3.12 shows a little test I ran on some different browsers.
Figure 3.12 Here's how different browsers interpret different font-weight settings.
Can you see more than two weights for any given browser among these results? Nor can I. I even tried different fonts, but to no avail. There really are only two results for all the font-weight values—bold or normal. Boldness variations would be a nice way to show a hierarchy in all kinds of data, especially when you could easily generate the different numerical values mathematically from middleware (for example, ASP or PHP) code to automatically highlight results that cross certain thresholds. In the following section, I show you a relatively simple and useful representational method that the browser makers could give us designers. Certainly there's room for improvement here, as the results show.
Font-Variant Property
Example: blockquote {font-variant:small-caps;}
Values: small-caps, normal
This property accepts just one value (besides normal) and that is small-caps. This causes all lowercase letters to be set in small caps, like this
h3 {font-variant:small-caps;}
I often use small-caps with the first-line pseudo-class, which allows you to specify a style for the first line of an element. Typically you would use it on a paragraph (see Chapter 2). Again, use this styling sparingly because text in all uppercase is harder to read because it lacks the visual cues provided by the ascenders and descenders of lowercase type.
The Font Property Shorthand
Example: p {font: bold italic small-caps 12pt verdana, arial, sans-serif;}
<p>Here's a piece of text loaded up with every possible font property.</p>
The code above produces the result in Figure 3.13 .
Figure 3.13 It only takes one line of CSS to create this font styling.
The font property is a nifty shortcut that lets you apply all of the font properties in a single declaration; this helps reduce the amount of CSS you have to write to achieve your desired font styling. You have to sequence the values in the correct order, however, so that the browser can interpret them correctly.
Two simple rules apply:
Rule 1: Values for font-size and font-family must always be declared.
Rule 2: The sequence for the values is as follows:
- font-weight, font-style, font-variant, in any order, then
- font-size, then
- font-family
Text Properties
So now that you've looked at how to get the font you want, it's time to look at how to style text. If you want to indent a paragraph, create a superscript such as the 6 in 106, create more space between each letter of a headline, and many other type formatting tasks, you need to use the CSS text properties.
There are eight text-related CSS properties:
- text-indent
- letter-spacing
- word-spacing
- text-decoration
- text-align
- line-height
- text-transform
- vertical-align
Text-Indent Property
Example: p {text-indent:3em;}
Values: any length value (positive or negative)
Because I have already touched on it, let's start with the text-indent property. This property sets the start position of the text box in relation to the containing element. Normally, the left edge of the text box (the start of the first line, in the case of a multiple line block) and the left edge of the container are the same.
If you set a positive value to the text-indent, then the text moves to the right, creating an indented paragraph ( Figure 3.15 ).
Figure 3.15 Set a positive value for the text-indent property to create an indented paragraph.
If you set a negative value, the first line hangs out to the left of the containing element. Be careful when you use negative margins to create a negative indent—in such a case, the first line of text actually hangs outside of its container, so make sure that there is a place for the hanging text to go. If the containing element abuts another element to its left, then the hanging text overlaps the latter element, or if it's close to the edge of the browser window, it is clipped ( Figure 3.16 ).
Figure 3.16 This paragraph has a negative indent for the right margin but no corresponding left margin value, which causes the hanging text to be clipped.
The way to avoid this problem is always to specify a positive left margin value greater than the specified negative indent. In Figure 3.16, the negative indent is –1.5 ems, but in Figure 3.17 , there is also a left margin value of 2 ems.
Figure 3.17 This paragraph has a negative indent for the right margin and a corresponding left margin value that creates enough space for the hanging text on the right.
The code for the paragraph in Figure 3.17 is as follows
p {text-indent:1.5em; margin-left:2em; border: 1px solid red;}
Hanging paragraphs help give text that professionally styled look and give the reader clear entry points into the text blocks.
It's good practice to set indents and related margins in ems so that the indent remains proportional to the line length if the user (or you) change the text size. In the case of a hanging indent, proportional sizing ensures that enough space for the hanging text is created, regardless of how large the user might scale the font.
If space is tight and you don't want spaces between paragraphs, you can set the margin top and margin bottom values of the paragraphs to 0 and use indents or negative indents instead of vertical space to provide a clear indication of where each paragraph starts.
Letter-Spacing Property
Example: p {letter-spacing: .2em;}
Values: any length values (positive or negative)
This property produces what print designers call tracking, the overall spacing between letters. Positive values increase letter-spacing, while negative values decrease it. I highly recommend you use relative values, such as ems or percentages, rather than absolute values, such as inches or pixels, so that the spacing remains proportional even if the user changes the font size. Figure 3.18 gets you started.
Figure 3.18 In this example, you can see how changing the letterspacing value changes the look of your text.
As you can see, you can give headlines that professional touch by tightening them up a bit; the default letter spacing appears more and more loose as the text gets larger.
Generally, body copy doesn't need changes to the letter spacing, although it's a personal preference, and you can give your pages a unique look if the type is a little tighter or looser than is typical. Just go easy, as too much either way makes the type hard to read. Note the text and headline I tightened in Figure 3.18 only have .05em (a twentieth of an em) of letter spacing removed from between each character; much more and the letters would start to mush into each other. Generally, very small values, such a 0.1em, give the desired result; although it's only a small amount of space, it is inserted (or removed) between every character).
Word-Spacing Property
Example: p {word-spacing: .2em;}
Values: any length values (positive or negative)
Word spacing is very similar to letter spacing except, as you might imagine, the space changes between each word rather than between each letter. The first observation you should make here is that CSS treats any character or group of characters with white space around them as a word. Second, even more than letter spacing, word spacing can easily be overdone and result in some very hard to read type ( Figure 3.19 ). Easy does it.
Figure 3.19 Word spacing is one of those styles that is easy to overdo.
Text-Decoration Property
Example: .retailprice {text-decoration: strikethrough;}
Values: underline, overline, strikethrough, blink
No, you can't hang holly and little bells on it, but you can underline, overline, strike-through, and blink (but don't do it, please, because it is s-o-o-o-o annoying) text using this property.
The primary application of text decoration is controlling the underlining of links. Think long and hard before you add underlining to text that is not a link; in fact, unless it's a link, don't underline it. Perhaps if you have a column of numbers, you might underline the last one before the total, or something like that, but Web users are so used to underlining as the visual cue for a link that you are setting them up for frustration, disappointment, and a lot of useless clicking if you underline text that is not a link.
Text-Align Property
Example: p {text - align: right;}
Values: left, right, center, justify
There are only four values for this property: left, center, right, and justify. The text aligns horizontally with respect to the containing element and you must set the property on the containing element; in other words, if you want a h1 headline centered with in a div, set the text-align of the div, not the h1. Figure 3.20 shows the four possible text-align values in action.
Figure 3. 20 Text alignment has four different values, each of which is demonstrated here.
Line-Height Property
Example: p {line-height: 1.5;}
Values: any numerical value (no value type is needed)
line-height is the CSS equivalent of leading (pronounced like the metal) in the world of print. Leading creates space between the lines of a block of text. Leading is defined not as the height of the space between the lines, but as the distance between the baseline of one line and the next. For the sake of readability, leading is greater than the height of the type so that there is space between the lines. By default, browsers set leading proportionately to the font size—typically at 118 percent of the font size according to my tests—so there is always consistent space between the lines no matter what the font size.
The simplest way to set the leading is to use the font: shorthand property and write a compound value for both font size and line height in one. For example:
div#intro {font: 1.2em/1.4;}
In this case, the leading is 1.4 times the font size of 1.2 ems. Note that you don't need any units, such as ems or pixels, specified for the line-height part of the value, just a number. In this case, CSS simply takes the calculated size of whatever number of onscreen pixels 1.2 ems works out to be and multiplies it by 1.4 to arrive at the line height. If you later increase the font size to 1.5 ems, the line height (leading) is still 1.4 times the calculated amount of 1.5 ems. If the line height had been specified in a fixed unit such as pixels and you increased the font size, then the lines of text would overlap one another.
It's worth noting that any line height greater than the text height is shared both above and below the text. Let's take a simple example in pixels to illustrate this point, although for the reasons I gave earlier, using pixels is not the ideal way to set line height. However, it's easier to understand the math if you use pixels here. If you have a font size of 12 pixels and you set the line height to 20 pixels, the browser adds 4 pixels of space above the line of type and four below; 12 + 4 + 4 = 20. In the normal course of events, you don't notice this because the overall look in a multiline paragraph of text is that there are 8 pixels of space between each line. However, this might have a bearing for you on the top and bottom line of type, which, in fact, only have 4 pixels of space above and below them respectively.
Text-Transform Property
Example: p {text-transform: capitalize;}
Values: uppercase, lowercase, capitalize, none
text-transform changes the capitalization of text within an element. You can force a line of text to have initial letters capitalized, all text uppercase, or all text lowercase. Figure 3.21 shows the various options.
Figure 3.21 The text-transform property can turn text into uppercase or lowercase as well as perform other party tricks.
capitalize capitalizes the first letter of every word. This emulates the style of many headlines in ads, newspapers, and magazines, except that a human applying such styling tends to leave the capitalization off minor words such as "of", "as", and "and", as in "Tom and Jerry Go to Vegas." CSS capitalization simply produces "Tom And Jerry Go To Vegas." However, it's a nice effect for headlines, and if your content is coming from a database or another source such as XML, you can get this effect without touching the markup.
Use font-variant if you want large and small caps. Think also about tightening up the visual appearance with a small negative letter-spacing value (see "Letter-Spacing Property" earlier in this chapter).
Vertical-Align Property
Example: vertical-align:60%
Values: any length value, sub, sup, top, middle, bottom
Vertical-align moves type up or down with respect to the baseline. As this example demonstrates, one of the most common uses is for superscript and subscripted numbers in formulas and mathematical expressions, such as x4-y-5 or N3O. It's also the correct way to style asterisks and other markers within text to indicate footnotes.
The XHTML tags sup and sub create superscript or subscript text automatically, but as Figure 3.22 shows, it's worth using vertical-align and text-size in combination to produce a more pleasing result.
Figure 3.22 Vertical-align improves the appearance of the default XHTML tags for creating subscript and superscript
Here's the code for this example
<style type="text/css"> body {font-family:verdana, arial, sans-serif; font-size:100%;} h4 {margin: 1.4em 20px .5em; color:#069;} p {margin: 0 20px;} p.largertext {font-size:2em; margin-top: 1em;} span.raised {font-size:.4em; vertical-align:50%;} p.custom sub {vertical-align:sub; font-size:65%;} p.custom sup {vertical-align:65%; font-size:65%;} p.customsmall {font-size:.8em;} </style> </head> <body> <p class="largertext">Vertical-align <span class="raised">can be used in all kinds of</span> interesting ways.</p> <h4>This example uses default settings of the xhtml tags "sub" and "sup"</h4> <p>Enjoy mountain spring H<sub>2</sub>O - it's 10<sup>5</sup> times better than tap<sup>†</sup> water!</p> <p><sup>†</sup><em>This means water provided through a municipal distribution system</em></p> <h4>This example uses classes for custom vertical alignment and type sizes</h4> <p class="custom">Enjoy mountain spring H<sub>2</sub>O - it's 10<sup>5</sup> times better than tap<sup>†</sup> water!</p> <p class="customsmall"><sup>†</sup><em>This means water provided through a municipal distribution system</em></p> </body>
Using Font and Text Styles
Using the markup we developed in Chapter 1, let's look at how we can transform a very ordinary looking page into a more professional looking piece. Figure 3.23 shows the unstyled markup:
Figure 3.23 Here's our unstyled markup from the Chapter 1 example.
By applying only styles we learned in this chapter plus the margin property, the page suddenly looks like someone actually designed it ( Figure 3.24 ).
Figure 3.24 Here's the Chapter 1 sample markup styled with font and text styles
Here are the styles:
-
body {font-family:verdana, arial, sans-serif; font-size:100%; margin:1em 2em;}
These are baseline styles for the font and page margins. The font-family is inherited by all elements and the margins move all the elements in from the edges of the page.
-
* {margin:0; padding:0;}
Here we "neutralize" all the default margins on the elements that eat up so much vertical space in the unstyled version. We also do the same for the padding to enable us to apply consistent styles to the lists for all browsers. By removing all the default margins and padding, only elements that we decide should have them, have them.
-
h3 {font-size:.7em; word-spacing:1em; letter-spacing:-.05em; margin:.5em 0;}
Here we've set tight letter spacing and wide word spacing.
-
h1 {font-size:1.1em; text-transform:uppercase; text-align:center; letter-spacing:.2em; margin: .5em 0;}
The header is now centered with increased letter spacing and all capitals.
-
p {font-size:.75em; line-height:1.5em; text-indent:-1.75em; margin: 0.5em 0 .75em 1.75em;}
Here we've reduced the type size, increased the line height, and set a negative indent for the first line.
-
ol {margin-left:6em; font-size:.75em; line-height:1.5; font-style:italic;}
The large left margin indents the list. We've also italicized the list and increased line spacing for any lines that may wrap.
-
a {margin-left:6.5em; font-size:.7em;}
We set the left margin to make the link sit under the list text.
-
a:hover {text-decoration:overline underline;}
When the link is hovered, we get an interesting above and below underline. (Hovered behavior not shown in Figure 3.24.)
-
ul {margin-left:6em; font-size:.75em; line-height:1.75; font-style:italic;}
This list is also indented and italicized.
-
ul a {font-size:1em; margin:0;}
The list items are links so we style these differently from non-list links using a contextual selector
-
sup {vertical-align:35%; font-size:65%;}
A custom treatment of the sup tag.
-
div#homepagefooter p {font-size:.7em; font-weight:bold;}
We've created small bold type for the footer.
Remember that once styles like these are in a style sheet, they are applied to all the pages that link to it, so you can get a whole Web site's-worth of mileage out of the work you put into styling a page like this.