• home
  • forum
  • my
  • kt
  • download
  • Styling Text

    Author: 2007-07-19 10:21:01 From:

    The good news is that you do have some choice over fonts, and CSS expands the way you use the fonts by being able to add color, weight, height, spacingall kinds of features that add visual interest to the fonts you do choose. As you become more adept with CSS in general, you'll learn to combine graphics and text-based type to come up with increasingly sophisticated type designs.
    In this tutorial, you'll learn about font and text styles, along with some of the additional style properties that will affect your text but not necessarily be limited to use with text. You'll also learn about additional selector types that have not yet been introduced to you.

    Now that you have a taste of what CSS can do, you'll take it further and begin to style your text. Historically, CSS has been used more to style text than just about anything, largely because of good support for much of the text-related styles that were in CSS 1.0. Some new options have appeared since then, giving you even more control over the way you manage text for web documents. The basic principles for how text is styled in CSS come from traditional typography, although limitations based on both CSS and browser support have prevented certain growth in the area of web-based type.

    A warning from the start, though: Working with fonts can be complicated. First, you must understand that, in terms of available fonts for text-based type on the Web, there's dependence upon a person's operating system and installed font base. If a specific font is not installed on someone's machine, that person will not be able to view the font. The same limitation existed for presentational HTML, too, and not much has changed since then. Then there is a major browser flaw in font sizing that makes using font sizes a real pain. Over these concerns you are essentially powerless, except in what you can learn in terms of how to manage them. So bear with me through the details, okay?

    The good news is that you do have some choice over fonts, and CSS expands the way you use the fonts by being able to add color, weight, height, spacingall kinds of features that add visual interest to the fonts you do choose. As you become more adept with CSS in general, you'll learn to combine graphics and text-based type to come up with increasingly sophisticated type designs.

    Within the CSS specification, properties for managing typography are found in two primary places. The first is in font-related properties, which are all specific to the way a font is chosen and then displayed. The second is text-related properties, in which text is further managed, usually without some manipulation to the actual font. Some font features come from the more general visual category of styles and can be used with (but are not limited to) text.

    In this tutorial, you'll learn about font and text styles, along with some of the additional style properties that will affect your text but not necessarily be limited to use with text. You'll also learn about additional selector types that have not yet been introduced to you.

    Choosing fonts for document design can be confusing for those who have little exposure to design or typography. Fortunately, there are some good rules of thumb to fall back on.

    Fonts have traditionally been broken down into groups, referred to as font categories or, as in CSS, font families. Fonts are grouped based on like characteristics. In CSS, there are five general categories:

    • Serif A serif font is one that has flourishes on the letter, referred to as, you guessed it, serifs. These fonts are thought to be excellent for body text, especially in print, and are very suitable for header and other text such as captions. Serif fonts that might be familiar to you include Times and Georgia, both of which are widely used on the Web.

    • Sans-serif The term sans-serif means "without serif" and describes, quite literally, fonts that have no flourishes. Instead, sans-serif fonts tend to have rounded, wider letters. Typically thought to be best for headers in print, they are anecdotally thought by many to be the better choice for body text onscreen. They aren't always the best choice for very small text or for italicized text, however. Familiar fonts within this category include Arial, Helvetica, and Verdana.

    • Monospace Monospace fonts are fonts whose letters are all the same width. They are typically used to describe programming code samples. In recent years, they've been popular in design, giving a very "grunge" look to the designs in which they are used. However, you'll typically limit use of monospace fonts to code samples. The most common monospace font in computing is Courier.

    • Fantasy Fantasy fonts, also known as decorative fonts, are fonts with unusual features. They tend to be elaborate and useful for headers or small areas of text, and not very useful for body text because their decorations make them difficult to read. You will rarely, if ever, use a fantasy font in CSS because they are very numerous and are not found with any consistency on most computers. An example is the Western font.

    • Cursive Cursive fonts are also referred to as handwriting fonts. They mimic cursive handwriting and are often filled with flourishes. As with fantasy fonts, cursive fonts are rarely applied with CSS. Many designers set fantasy or cursive fonts on graphics and use them as decorative typographic elements within a design. A common cursive font is Lucida Handwriting (see Figure 9-1).

      Figure 9-1. I used inline CSS to style each line of text with the font specified.

      [View full size image]

    Fonts that are common to almost everyone's system these days include Arial, Helvetica, Verdana, Times, Georgia, and Courier. Tahoma, Trebuchet, and Lucida fonts are fairly widespread because they ship with all Windows versions and were originally included in Microsoft's Web Font Pack, a free set of fonts that Microsoft distributed in the relatively early days of the Web.

    If you're just starting out, it's best to stick to a very simple scheme with fonts. You can do one of the following:

    • Choose one font, a common serif or sans-serif, and use that same font for everything. Modify size, weight, color and other styles to gain interest.

    • Choose two fonts, a common serif and a common sans-serif. Use the serif for all headings, captions, and other text; use the sans-serif for body text. (This option is very common on the Web.)

    • Choose two fonts, a common sans-serif and a common serif. Use the sans-serif for all headings, captions, and other text; use the serif for body text. (Also a common option for the Web, this technique has long been used in the print world; look at any newspaper or book, and you're likely to see this combination in use.)

    As you become more adept at using fonts, you might want to get more creative, but, typically, sticking to one of these options will make your documents look more professional and consistent.

    With an idea of what you can reasonably choose from, it's time to go ahead and apply font families to your text. To do this, you select the text in question, and then use the font-family property and an associated value.

    The value you use for the font-family property can be a single font name, a font family keyword, or a series of names followed by a font family keyword.

    Single Font Names

    Choose this technique only when you are absolutely certain that your audience has the font in question.

    body {font-family: Arial;}
    


    This sets the default font for all documents to Arial. The problem with this technique is that if the user doesn't have Arial installed on his or her machine, the browser will use the default fontthis is typically Times and might be quite a different look than what you're after.

    Font Family Keywords

    Font family keywords in CSS match the family names described in the last section: serif, sans-serif, monospace, fantasy, and cursive.

    h1 {font-family: fantasy;}
    


    This would apply the default fantasy font on your visitor's machine to all h1 headers. The problem with using keywords is that you have no control over which font that will be. As a result, keywords are typically used as a fallback method. So, if you're choosing a single font name, you can also add the related keyword after the font you've chosen:

    h1 {font-family: Arial, sans-serif;}
    


    In the fairly unlikely event that Arial isn't installed on your user's machine, it defaults to a sans-serif font on the user's machine.

    Multiple Names

    A technique that affords more control is using multiple family names. This means choosing fonts from the same family used in a specific order:

    body {font-family: Arial, Helvetica, Verdana, sans-serif;}
    


    The browser will look for the first named font; if it doesn't exist, it will apply the second, or third. Additionally, you'll note that I've added the family keyword name.

    In Example 9-1, I've created a style sheet to demonstrate using the font-family property.

    Example 9-1. Applying fonts to page elements
    body {font-family: Georgia, Times, serif;}
    h1, h2 {font-family: Arial, Helvetica, sans-serif;}
    


    You'll notice that I've declared a font for the body but not the paragraphs. This provides a default for all text that falls into the body of a document.

    In this example, the paragraphs simply inherit the font family from the body element. Notice also that I've grouped the h1 and h2 because I want them to have the same font. Figure 9-2 shows the results.

    Figure 9-2. A sans-serif is used for the headers, with a serif font chosen for the body.

    [View full size image]


    Of course, I haven't defined any other sizes or styles just yet. As a result, the browser styles are applied, so the default size for h1, h2, and paragraphs is determined by my browser until I create additional rules to control those styles.

    In this section, you'll learn to size fonts using the font-size property along with an absolute, relative, length, or percentage value.

    Absolute and Relative Keywords

    Absolute keywords size fonts based on the way that the browser computes their size. The keywords available are xx-small, x-small, small, medium, large, x-large, and xx-large. Here, I've applied an absolute keyword to paragraph text:

    p {font-size: medium;}
    


    The medium size is typically equivalent to the browser's default size for that element. Figure 9-3 shows all the keywords as applied to default browser text.

    Figure 9-3. Absolute keyword sizing within a web browser.


    Where absolute keywords are dependent upon the browser's computation of fonts, the relative keywords of larger and smaller relate to the size of the parent element. So, if I've set my body font size to medium, I can use the relative keyword of larger to change the size to large, or smaller to change the size to small. Just remember that relative keywords always relate to an already defined size, whether it's defined by a keyword, length, or percentage value.

    Length Values

    Length values are used with many properties. They include three relative and five absolute values. Relative values are em, ex, and px; absolute values are pt, pc, in, mm, and cm. Absolute values should not be used for the screen, although they are useful when creating print style sheets.

    The most commonly used length values for type on the Web are pixels and ems because, technically, they are both scalable, which is appropriate for screen. There's a major problem, however: Microsoft Internet Explorer for Windows does not scale pixels. This is a terrible oversight that has caused real problems, especially because you want to offer your vision-impaired users scalable sizing. Compare the values on the left to the values on the right, where I've bumped up the browser text (in IE, View > Text Size) from its default size of medium to larger (see Figure 9-4).

    Figure 9-4. Comparing font sizes in Internet Explorer 6.0.


    You'll note that the em values scale, but the pixels and points do not. The pixels should scaleand they do in browsers with correct font-sizing support. The points (which I advise you not to use for screen) remain the same size because they are absolute values, meaning they should never scale. As a result, many web designers advocate the use of ems over pixels. You'll note, however, the teeny text on the left. This can also cause serious problems if people have their browsers set to a smaller font size than medium.

    Percentages

    Percentage values in font sizing are always relative to another value, such as a keyword or length value. So, if I set my body font size to 1em and then set my H1 header to 150%, I'll end up with a larger h1 than the body font size, which is relative to the browser default:

    body {font-size: 1em;}
    h1 {font-size: 150%}
    


    Percentages are particularly helpful in working around browser limitations in font sizing. The reason is that percentages are also scalable. As a result, many workarounds for the pixel problem in IE have been achieved by combining ems and percentages. Still, many designers prefer to go with pixels because of their more consistent rendering, at the cost of better accessibility.

    NOTE

    You'll use a variety of sizing options throughout this book, to get the hang of it. For more information on font sizing problems, see Owen Briggs's article "Text Sizing," at http://www.thenoodleincident.com/tutorials/box_lesson/font/TOC_Styling_Text.html.

    Whew! That was a lot of detail for a book that's supposed to be straightforward. But to be fair to you and ensure that you've got a solid foundation, I had to do it. Now let's get on with the show!

    Along with their family and size, fonts can have weight and style. Font weight refers to how bold (or not bold) a font is. Font style refers to different faces that might exist within a given family.

    Font Weight

    Defining the weight of the font is done by using the font-weight property combined with an associated value. Values for weight include numeric (100-900, where 100 is very light, 900 is the darkest, and 400 is normal), the keyword normal (corresponding to a weight of 400), the keyword bold (equivalent to a weight of 700), the keyword bolder (specifies the next higher weight), and the keyword lighter (specifies the next lighter weight).

    Example 9-2 shows a style sheet with a variety of weights applied.

    Example 9-2. Styles describing font family, size, and weight
    body {font-family: Georgia, Times, serif; font-size: 1em; font-weight: normal;}
    h1, h2 {font-family: Arial, Helvetica, sans-serif;}
    h1 {font-size: 150%; font-weight: bold;}
    h2 {font-size: 130%; font-weight: lighter;}
    .accent {font-weight: 700;}
    


    Figure 9-5 shows the text used earlier in the tutorial with these styles applied.

    Figure 9-5. Applying weight to the body, headers, and an accent class.

    [View full size image]


    NOTE

    The use of numeric values 100 to 900 is not well supported. It's a good rule of thumb to use only those number values that correspond directly to a known weightfor example, 400 for normal, 700 for bold.


    Font Style

    Font styles help alter the face. To apply a font style, you use the font-style property with a value of normal, italic, or oblique.

    The normal value is used only when you're specifically concerned about text being rendered in its normal weight. Otherwise, it's the default and unnecessary to use.

    Oblique faces are slanted faces that are appropriate for electronic text. The oblique value is truly useful only when a font has an oblique face resident on a user's computer, which doesn't apply to the majority of fonts with which you will be working. If there is no oblique face for the font, the font will appear as italic.

    The italic value italicizes the font. Bottom line? Your best value for the font-style property will be italic in almost all cases (see Example 9-3).

    Example 9-3. Styles describing font family, size, weight, and style
    body {font-family: Georgia, Times, serif; font-size: 1em; font-weight: normal;}
    h1, h2 {font-family: Arial, Helvetica, sans-serif;}
    h1 {font-size: 150%; font-weight: bold;}
    h2 {font-size: 130%; font-weight: lighter; font-style: italic;}
    .accent {font-weight: 700;}
    


    Figure 9-6 shows how the italics are applied to the h2 header.

    Figure 9-6. Adding a font style to the h2 element.

    [View full size image]
    This is the easy part! Text color uses the color: property, which, as you can see, does not have a font or text prefix.
    To apply a color to a font, simply use the color property along with an appropriate color value. You can refer to tutorial 8, "Working with Color and Images Using CSS," where I applied the color property in numerous cases and discussed color values at length.
    I want to color up the text a bit, so I'm going to apply color to my existing styles (see Example 9-4).
    Example 9-4. Coloring the text
    body {font-family: Georgia, Times, serif; font-size: 1em; font-weight: normal; color: black;}
    h1, h2 {font-family: Arial, Helvetica, sans-serif;}
    h1 {font-size: 150%; font-weight: bold; color: #999;}
    h2 {font-size: 130%; font-weight: lighter; font-style: italic; color: #333;}
    .accent {font-weight: 700; color: red;}
    

    You can see the headers change color in Figure 9-7.
    Figure 9-7. Applying color to the body, H1, h2, and class selectors.

    [View full size image]

    Of course, you can't see the red accent color applied to the accent class because of the nature of this book, but be sure to write up your styles and fire up your browser to check it out for yourself.

    Back in the days of presentational HTML, text was aligned using the align attribute and a corresponding justification value. CSS uses the exact same premise, but, of course, it's done outside the HTML using the text-align property. The values are the same and should be familiar to anyone who's ever used a word processor:

    • left Also referred to as ragged right, left justification sets the text flush left with lines breaking to the right. This is default behavior for all browsers and is the preference for all body text. text-align: left;

    • center This centers the text. Centered text is useful for styling headers, captions, and other accent text. It is very difficult to read long sections of centered text, so it's not best to use for body text. text-align: center;

    • right This places all text flush right, leaving a ragged left edge. text-align: right;

    • justify Justifying text means having the left and right edges be equally flush. This is done by calculating words and spacing within the available line length. It's commonly seen in print newspapers and magazines. It can create a very uniform, attractive look, but most people avoid it because the spacing can appear to be very awkward and, therefore, more difficult to read. text-align: justify;

    Figure 9-8 compares a paragraph with each alignment option applied.

    Figure 9-8. Left, center, right, and justified text.

    You can "decorate" text with CSSthat is, apply or remove a particular decorative value. This is done using the text-decoration property, with values as follows:

    • none This is used primarily to remove the default underlines from links. See tutorial 10, "Link Effects, Lists, and Navigation."

    • underline This places a line underneath the selected text. Usability specialists tend to shun underlined text because it can be confused with linked text.

    • overline This places a line above the selected text.

    • line-through This places a line through the selected text.

    • blink Yep, you read that right. This causes text to blink, a feature that was introduced (and used to the point of pain) by Netscape in the early days. It works in all contemporary browsers but Internet Explorer.

    Example 9-5 serves up an inline CSS sample for decorating text.

    Example 9-5. Decorating text with CSS
    <p style="text-decoration: underline;">This text is underlined</p>
    <p style="text-decoration: overline;">This text has an overline</p>
    <p style="text-decoration: line-through;">This text has a line-through</p>
    <p style="text-decoration: blink;">This text blinks</p>
    


    Figure 9-9 shows the results, with the exception of the blink.

    Figure 9-9. Decorating text with CSStry out the sample CSS to see the blink.

    Another very useful text property is text-indent. This enables you to indent text with CSS instead of spacer graphics or numerous nonbreaking space characters in your HTML.

    You can use any length value (described earlier this tutorial) that is fixed.

    p {text-indent: 45px;}
    


    This results in each paragraph having an initial indentation of 45 pixels (see Figure 9-10).

    Figure 9-10. Indenting paragraphs with a 45-pixel indent.

    [View full size image]


    You can use percentage values, too, which will be relative to the element's containing box (more on that in tutorial 12, "Positioning, Floats, and Z-Index"):

    p {text-indent: 40%;}
    


    This results in a deep indentation, which you can use from time to time for an unusual look (see Figure 9-11).

    Figure 9-11. Indenting using percentages.

    [View full size image]


    You can use negative length values to outdent text (see Figure 9-12).

    Figure 9-12. Outdenting text by setting margins and applying text-indent: -20px;.

    You can style the case of text and vary its font using two different properties.

    To transform case, you use the text-TRansform property and a value of capitalize, uppercase, lowercase, or none.

    To vary text, you use the font-variant property and a value of small-caps or normal (which is the default).

    Example 9-6 shows a document employing transformation and variants.

    Example 9-6. Transforming and varying text with CSS
    [View full width]
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>working with style</title>
    <style type="text/css">
    body {font-family: Georgia, Times, serif; color: black;}
    h1 {font-family: Arial, Helvetica, sans-serif; font-size: 24px;
    font-variant: small-caps;}
    h2 {font-family: Georgia, Times, serif; color: #999; font-size: 18px; font-style: italic;
     text-transform: lowercase;}
    .accent {font-weight: 700; color: red; text-transform: uppercase;}
    p {font-size: 16px; text-transform: capitalize;}
    </style>
    </head>
    <body>
    <h1>The Black Cat</h1>
    <h2>By Edgar Allen Poe</h2>
    <p>I married early, and was happy to find in my wife a disposition not
    uncongenial with my own. Observing my partiality for domestic pets, she
    lost no opportunity of procuring those of the <span class="accent">most</span> 
    agreeable kind. We had birds, gold fish, a fine dog, rabbits, a small monkey,
    and a cat.</p>
    <p>This latter was a <span class="accent">remarkably</span> large and beautiful animal,
     entirely black, and sagacious to an astonishing degree. In speaking of his intelligence,
     my wife, who at heart was not a little tinctured with superstition, made frequent allusion
     to the ancient popular notion, which regarded all black cats as witches in disguise.</p>
    <p>Pluto - this was the cat's name - was my <span class="accent">favorite</span> pet and
     playmate. I alone fed him, and he attended me wherever I went about the house. It was even
     with difficulty that I could prevent him from following me through the streets.</p>
    </body>
    </html>
    


    You can see how text-TRansform and font-variant work in Figure 9-13.

    Figure 9-13. Transforming and varying text.


    Browsers that provide full support for transforming and varying text will apply the styles regardless of the case your text is actually composed in. Of course, for sensible reasons, you'll want your text content to be treated normally in the document. This way, you can always change the styles without having to reauthor the document.

    NOTE

    Browser support for text-transform and font-variant is pretty good overall, but one known issue in contemporary browsers is that font-variant: small-caps; does not work in certain early versions of the popular Safari browser from Apple. The style simply won't be applied in any way, and the text will pick up only those styles that Safari does support.

    Referred to in traditional typography as leading, line height is the space between each line in a section of text. CSS enables you to control this using the line-height property, with length, number, or percentage values (see Example 9-7).

    Example 9-7. Adding line height to paragraphs with length, number, and percentage
    [View full width]
    <p style="line-height: 20px;">I married early, and was happy to find in my wife a
     disposition not uncongenial with my own. </p>
    <p style="line-height: 2;">Observing my partiality for domestic pets, she lost no
     opportunity of procuring those of the most agreeable kind. We had birds, gold fish, a fine
     dog, rabbits, a small monkey, and a cat.</p>
    <p style="line-height: 65%;">This latter was a remarkably large and beautiful animal,
     entirely black, and sagacious to an astonishing degree.</p>
    


    In the complete document, I set a body font to 14 pixels and then applied line-height inline for each paragraph I wanted to modify (see Figure 9-14).

    Figure 9-14. Variations in line height can lead to interesting effects.


    Typically, it's a good idea to stick to the font's default line-height for best readability.

    Another aspect of typography that CSS has picked up on is letter spacing and word spacing, handled by the letter-spacing and word-spacing properties, respectively. Values for each are lengths (see Example 9-8).

    Example 9-8. Letter and word spacing
    [View full width]
    <p style="letter-spacing: 10px;">I married early, and was happy to find in my wife a
     disposition not uncongenial with my own. </p>
    <p style="word-spacing: 0.5em;">Observing my partiality for domestic pets, she lost no
     opportunity of procuring those of the most agreeable kind. We had birds, gold fish, a fine
     dog, rabbits, a small monkey, and a cat.</p>
    


    The first paragraph will have 10 pixels between each letter, and the second will have 0.5 ems between each word (see Figure 9-15).

    Figure 9-15. Letter and word spacing.


    The results are unusual. Although you wouldn't normally use these styles in conservative documents, you can begin to see how using such styles can provide sophisticated design options.

    You can style the first letter of text (a drop cap) and the first line of text using the pseudo element selectors. You haven't seen these yet, so here's a look:

    :first-line
    :first-letter
    


    These get attached to the element to which you'd like the style to apply (see Example 9-9).

    Example 9-9. Using pseudo element selectors to style
    p:first-line {font-weight: bold; color: #333;}
    p:first-letter {font-style: italic; color: #999;}
    


    In Figure 9-16, I've applied these styles to text.

    Figure 9-16. Using pseudo element selectors to create first-line and first-letter styles.

    [View full size image]

    As with backgrounds, there's a shorthand property for font styles. These incorporate some of the font properties and the line-height property, but none of the text properties. What's more, you have to pay close attention to order when you use shorthand with fonts.

    The shorthand property is font: and the order of its values is as follows: font-style, font-variant, font-weight, font-size/line-height, font-family.

    p {font: italic small-caps bold 14px/15px Arial, Helvetica, sans-serif;}
    

    This will result in all paragraphs being italic, small-capped, and bold, with a font size of 14 pixels, a line height of 15 pixels (note the slash between them, the only time this symbol is ever used in CSS) and text in Arial, Helvetica, or a default sans-serif font.

    If you want to leave out any value, just keep the integrity of the rest of the order:

    p {font: bold 14px Arial, sans-serif;}
    

    This results in a 14-pixel bold Arial font. You can use shorthand any time you like; just be aware that, with fonts, order is imperative or your style sheet might not work.

    QUANTUM LEAP: UNSUPPORTED AND POORLY SUPPORTED FONT AND TEXT PROPERTIES

    Several poorly or completely unsupported styles are available in the current specification for fonts and text. I'd like to take a moment to mention them here, mostly because they're really cool. Also, I bring this up because eventually support for these properties will likely be more widespread.

    The font-size-adjust property enables you to set an adjustment value so that all your fonts appear relatively uniform in terms of their sizing. This would come in very handy because different fonts have different native sizing: Surely you've noticed that a 12-pixel Times font is smaller than a 12-pixel Arial font. Well, as soon as you begin to have multiple fonts, you might want to make them more visually uniform. By setting a font-size-adjust value, you normalize the size of the fonts so that all fonts within the style are sized consistently. You can see why this would be useful.

    The font-stretch property enables you to condense or expand text. This is helpful when you want to get some interesting effects.

    Finally, the text-shadow property enables you to create a drop shadow effect for your text. Won't this be cool when you can actually use it? The property allows for color and offset values, and will eliminate the need for graphics when the goal is simply to add a shadow effect to the text.

    I just know you're having fun now! You've got enough skill with images, color, and text to really create a nice-looking page or site.

    But, of course, there's lots more to learn with CSS. In the next tutorial, you'll take a look at the ways links are used in today's web design. Once we could style links with only limited options, but now we can have multiple styles of links, including multiple colors for all states, even hovers.

    You'll also learn about lists and how the combination of lists and links has become a mainstay of approaching contemporary navigationboth vertical and horizontal, helping you to create awesome and interactive interfaces with minimal or even no use of images.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      CSS (142)

    New

    Hot