Jump to content

Cascading Style Sheets/Fonts and Text

From Wikibooks, open books for an open world

Font Properties

[edit | edit source]
  • font-family — Sets the typeface.
  • font-style — Sets the style of the text, common values are normal and italic.
  • font-variant — Modifies the text, e.g. small-caps.
  • font-weight — Sets the thickness the text will be, values like bold and normal.
  • font-size — Sets the font size.
  • line-height — Sets the spacing between the baselines of adjacent lines of text.

Each of these is examined below in detail.

font-family

[edit | edit source]

W3C Specification CSS1 CSS2.1

The following is a simplified description of CSS font matching. See the CSS1 font matching or CSS2.1 font matching specification for the definitive description.

The value for the font-family property is a comma separated list of fonts in a prioritized order. The web browser will attempt to use the first font in the list. If the first font isn't available to the web browser it will attempt to use the second, and so on through the list. If none of the fonts are matched the web browser will use a default font. This might be a font selected by the user.

In the example below the web browser would try to use Verdana. If Verdana was not installed (or not available in an appropriate variant if font-variant is also specified) the web browser would try to use Helvetica. If Helvetica was not available it would try to use Arial.

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

Since there isn't a standard set of fonts that is available in all web browsers and operating systems it is possible that none of the named fonts will be matched. Five generic font families are defined to allow for this possibility. Web browsers will replace a generic font with the closest available font. The five generic families are: serif, sans-serif, monospace, cursive and fantasy.

You should always end a font-family list with a generic text-family. Otherwise you might, for example, end up with the user's default serif font where you wanted a sans-serif font. A generic font is always guaranteed to match so there is no point specifying alternative fonts after a generic font. On systems with a limited range of fonts it is possible that two or more generic fonts may be mapped to the same font. You can check which fonts your web browser uses for the generic fonts by looking at the example below. Are there five distinct fonts?

serif sans-serif monospace cursive fantasy

An ongoing problem for web designers is that they are not able to specify exactly the fonts that they require, because that they don't know which fonts the user will have installed. The way around this is to specify in the font-family list a more-or-less equivalent font from each possible client system. There are a number of useful references for determining this equivalence (here, for example).

For example, to use the font known on Windows as Impact, the following declaration is used.
font-family: Impact, Charcoal, sans-serif
Where 'Impact' is the Windows name, 'Charcoal' is the MacOS name, and 'sans-serif' is the generic fall-back for systems without either of these two.


font-style

[edit | edit source]

W3C Specification CSS1 CSS2.1

CSS1 and CSS2.1 define three values for this property: normal, italic and oblique. The initial value for this property is normal. Many font families do not define a separate italic version of the font, in which case the oblique version is used when font-style is set to italic.

CSS rules:

#para1 {
  font-style:normal
}

#para2 {
  font-style:oblique
}

#para3 {
  font-style:italic
}

Sample HTML:

    <p id="para1">This sentence should be in an upright version of the font.</p>
    <p id="para2">This sentence should be in an oblique version of the font.</p>
    <p id="para3">This sentence should be in an italic version of the font.
      Is it different to the oblique version?
    </p>

Example rendering:

This sentence should be in an upright version of the font.

This sentence should be in an oblique version of the font.

This sentence should be in an italic version of the font. Is it different to the oblique version?

font-variant

[edit | edit source]

W3C Specification CSS1 CSS2.1

CSS1 and CSS2.1 define two values for this property: normal and small-caps. The initial value for this property is normal. When small-caps is applied lowercase letters appear as scaled down uppercase letters. Uppercase letters and other characters are unaltered. The effects of these values is shown below.

CSS rules:

#para1 {
  font-variant:normal
}

#para2 {
  font-variant:small-caps
}

Sample HTML:

    <p id="para1">This sentence shows the effect of setting the
      Cascading Style Sheets property <code>font-variant</code>.
      Other characters: 1 2 3 % !
    </p>
    <p id="para2">This sentence shows the effect of setting the
      Cascading Style Sheets property <code>font-variant</code>.
      Other characters: 1 2 3 % !
    </p>

Example rendering:

This sentence shows the effect of setting the Cascading Style Sheets property font-variant. Other characters: 1 2 3 % !

This sentence shows the effect of setting the Cascading Style Sheets property font-variant. Other characters: 1 2 3 % !

font-weight

[edit | edit source]

W3C Specification CSS1 CSS2.1

The font-weight property sets the darkness of the font. CSS currently defines nine levels of darkness from 100, the lightest, to 900, the darkest. The number of distinct levels depends on the font-family. Some families may define all nine levels while most will only define one or two. The value normal is a synonym for 400 and bold is a synonym for 700.

The list below shows the different weights for the current family:

  • 100
  • 200
  • 300
  • 400 or normal
  • 500
  • 600
  • 700 or bold
  • 800
  • 900

The final two possible values for font-weight are lighter and bolder. When these values are used the web browser tries to pick a font from the current family that is lighter or darker than the font of the parent element.

Since most font families only have one or two weights it is usual to only use the values normal and bold.

For example, to make strong elements red instead of the bold used by most web browsers apply the following rule.

strong {
  font-weight:normal; /* remove the bold defined by the web browser */
  color:red
}

As another example you can make all hyperlinks bold.

a {
  font-weight:bold
}

Sample HTML:

    <p><strong>Note:</strong> in this text
       <a href="glossary#hyperlink">hyperlinks</a> are in boldface.
    </p>

Example rendering:

Note: in this text hyperlinks are in boldface.

font-size

[edit | edit source]

W3C Specification CSS1 CSS2.1

Before reading this section make sure you know how to change the default font size in all the browsers you use for testing web pages.

Make sure you understand the difference between screen pixels and CSS pixels. See CSS Lengths and units.

Font size is one of the more problematic areas of web design. The most common complaint of web surfers is that the font size is too small on many pages. (See Jakob Nielsen's Top Ten Web Design Mistakes of 2005.) A frequent request from customers buying a web site is for the font to be made smaller so more information can be crammed on to the page. To make matters worse, most users aren't taught how to change the default font size used by their web browser. (If you ever teach a class how to use a web browser, changing the font size and colors is one of the most important things you can teach.) Another issue is that web designers tend to be young with comparatively good eyesight. Just because you prefer to read text that is 60% of the out-of-the-box default font size doesn't mean your target audience can read text at that size.

Some users do change their default font size and web pages should respect their choices. Ideally all the important information on a page should be at least as large as the user's default font size. Important information includes publication dates, links to the site's privacy policy, etc. Small print should be reserved for unimportant text such as statements that the page is valid HTML, conforms to WCAG Double-AA, etc. and effects such as superscripts that are normally rendered in a smaller size.

Lengths in CSS pixels (px) or absolute units (pt, pc, mm, cm and in) do not respect users' preferences. In fact using these units prevents users from easily changing the size of the font if they find it too small or too large. For example, in Internet Explorer for Windows the user has to select 'Internet Options...' from the 'Tools' menu, then click on the 'Accessibility...' button on the 'General' tab and check the box to 'Ignore font sizes specified on web pages' if they want to change the size of a font given in any of these units. This isn't user friendly.

The values that do respect users' preferences are length in ems or exs, percentages and keyword values. There are seven 'absolute' keyword values that scale the font relative to the user's default font size and two 'relative' keyword values that scale the font relative to the parent element. The 'absolute' keywords are

  • xx-small
  • x-small
  • small – the user's default font size in IE/win v6 Quirks Mode and IE/win v5 regardless of rendering mode.
  • medium – the user's default font size in Standards Mode.
  • large
  • x-large
  • xx-large

The two relative keywords are smaller and larger.

Most web designers prefer to use ems. Font sizes in ems, exs and percentages are calculated relative to the font size of the parent element. 1em is equal to 100%. The following example demonstrates this.

#span1 {
  font-size:0.5em;
  color:red
}

#span2 {
  font-size:5em;
  color:green
}

#span3 {
  font-size:0.4em;
  color:magenta
}

Sample HTML:

    <p>The <span id="span1">text <span id="span2">size 
      <span id="span3">changes </span></span></span>a lot.</p>

Example rendering:

The text size changes a lot.

Since 0.5 times 5 times 0.4 equals 1 the text in the last span should be the same size as the text in the parent paragraph.

Using ems in Internet Explorer

[edit | edit source]

If you use ems for the font-size in a page viewed with Internet Explorer you need to be aware of a quirk of Internet Explorer. On a Windows PC save the two files given below in the same directory and view IE_font_size_bug.htm with Internet Explorer. (This example has been tested in IE/win v5.0, v5.5 and v6.0.)

IE_font_size_bug.css

p {
  font-size:1em
}

IE_font_size_bug.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <title>IE font size bug</title>
    <link rel="stylesheet" type="text/css" href="IE_font_size_bug.css">
  </head>
  <body>
    <p>Internet Explorer has a little problem with ems.</p>
  </body>
</html>

Set the default font size to medium, smaller and smallest. (Use the 'Text Size' submenu of the 'View' menu if you don't have the Size button on your toolbar.) The height of the text is shown in the following table.

Default font size Height of a capital letter Height of an em
Medium 11 screen pixels 16 screen pixels
Smaller 9 screen pixels 13 screen pixels
Smallest 6 screen pixels 12 screen pixels

At six pixels high letters become blurred splodges on the page and are effectively unreadable.

There is a simple fix. Add an extra rule to IE_font_size_bug.css like so:

body {
  font-size:100% /* Keeps IE happy when the user sets the default size to 'smallest'. */
}

p {
  font-size:1em
}

In theory setting the font-size to 100% shouldn't change anything. However, if you view the page with the new stylesheet you will find the size of 'smallest' text has changed.

Default font size Height of a capital letter Height of an em
Medium 11 screen pixels 16 screen pixels
Smaller 9 screen pixels 13 screen pixels
Smallest 9 screen pixels 12 screen pixels

Nine pixel high letters are quite readable if you have good eyesight and/or a large monitor.

It is a good idea to always set the font-size of the body to a percentage to deal with this quirk. It is also a good idea to leave a comment explaining why the font size declaration is there so that someone else doesn't remove an apparently redundant rule when they take over responsibility for your stylesheet.

Problems with nesting

[edit | edit source]

You can run into problems using ems or percentages when you set the font-size property using a type selector. In the example below each of the nested div elements matches the selector and so the size of the text is halved each time. The text in the innermost division is 1/16 of the user's default font size. You will probably struggle to read the example rendering unless you increase your default font size significantly.

CSS rules:

body {
  font-size:100% /* Keeps IE happy when the user sets the default size to 'smallest'. */
}

div {
  font-size:0.5em;
  border:1px dotted green;
  padding:1em
}

Sample HTML:

    <div>
      This division contains
      <div>
        another division that contains
        <div>
          another division and so on
          <div>
            until the text is tiny.
          </div>
        </div>
      </div>
    </div>

Example rendering:

This division contains

another division that contains

another division and so on

until the text is tiny.

This problem is often found with lists where it is tempting to set the font-size of the li element. When someone adds a sub-list in the future the text of the sub-list is far too small or far too large depending on the scale factor. The solution is to use an ID selector to target the outermost element of the nested group, e.g. the outermost ul element for nested lists.

Problems with tables and forms

[edit | edit source]

If you are using tables or forms you may find you need to use the following rule to get the text in these elements to scale properly with the user's preferences:

table, input, select {
  font-size:100%
}

line-height

[edit | edit source]

W3C Specification CSS1 CSS2.1

The line-height property defines the minimum distance between the baselines of adjacent lines of text. The distance may be increased if necessary to fit images, etc. on the line. It is expressed as a ratio between the height of the font and the line spacing. The height of a font is defined as the distance between the baseline and the top of a capital letter. Some letters may have descenders that drop below the baseline. In some fonts there may also be ascenders the rise above the top of a capital letter.

In the example below the green band behind each line runs from the baseline up to the font height. The first line shows capital letters. The second line shows lowercase letters with descenders. The third line shows capital letters with accents.

A B C

p q y

É Ñ Ô

The line-height can be given as either a simple number, a length or a percentage. If it is given as a simple number or a percentage this is multiplied by the font height to determine the space between the lines. The next example demonstrates how this paragraph appears with four different values for the line-height. The font is enlarged in the example to make the line spacing easier to see.

#para1 {
  line-height: 1
}

#para2 {
  line-height: 1.2em
}

#para3 {
  line-height: 160%
}

#para4 {
  line-height: 2
}

line-height = 1 or 100% or 1em

The line-height can be given as either a simple number, a length or a percentage. If it is given as a simple number or a percentage this is multiplied by the font height to determine the space between the lines. The next example demonstrates four different values for the line-height. The font is enlarged in the example to make the line spacing easier to see.

line-height = 1.2 or 120% or 1.2em

The line-height can be given as either a simple number, a length or a percentage. If it is given as a simple number or a percentage this is multiplied by the font height to determine the space between the lines. The next example demonstrates four different values for the line-height. The font is enlarged in the example to make the line spacing easier to see.

line-height = 1.6 or 160% or 1.6em

The line-height can be given as either a simple number, a length or a percentage. If it is given as a simple number or a percentage this is multiplied by the font height to determine the space between the lines. The next example demonstrates four different values for the line-height. The font is enlarged in the example to make the line spacing easier to see.

line-height = 2 or 200% or 2em

The line-height can be given as either a simple number, a length or a percentage. If it is given as a simple number or a percentage this is multiplied by the font height to determine the space between the lines. The next example demonstrates four different values for the line-height. The font is enlarged in the example to make the line spacing easier to see.

Look closely at the descenders in the example with a line-height of 1. You will probably notice at least one point where a descender touches a letter in the line below. Most web browsers default to a line-height of 1.2. A number of web designers feel that a line-height of 1.6 is more readable, particularly if the font size is relatively small.

Shorthand property

[edit | edit source]

W3C Specification CSS1 CSS2.1

The font shorthand property can be used to set the five individual font properties and the line-height property in a single declaration. The font has two methods for setting the individual properties, by specifying a combination of individual properties or by giving a single keyword that selects a predefined set of individual values. The second option is only available in CSS2.1.

Combination of individual properties

[edit | edit source]

The syntax for combining individual properties is a little complicated. The properties are given in the following order:

  • none, one or more of font-style, font-variant and font-weight in any order;
  • optionally followed by font-size;
  • if font-size is present it may be followed by a slash, /, followed by the line-height;
  • followed by the font-family, which must be present.

An example containing all the components is:

p {
  font: bold italic small-caps 150%/1.4 Arial, Helvetica, sans-serif
}

Notice that the 150% means that the font size is one and half time the font size of the parent element. The /1.4 then sets the line height to 1.4 times the font size of the current element. Also notice that the font family is a comma separated list of families in order of preference.

If some of the properties are omitted they are set to their initial values. For example,

p {
  font: monospace
}

is equivalent to

p {
  font-family: monospace;
  font-style:normal;
  font-variant:normal;
  font-weight:normal;
  font-size:medium;
  line-height:normal
}

Keyword

[edit | edit source]

The keyword values refer to the system fonts used by the web browser for items such as menus. The keyword values are:

caption ; the font used for buttons, drop-down lists, etc.
icon ; the font used to label icons.
menu ; the font used by drop-down menus.
message-box ; the font used by dialog boxes.
small-caption ; the font used for labelling small controls.
status-bar ; the font used in the status bar.

The keyword values set all the individual properties to match the corresponding system font. The individual properties can then be overridden by additional declarations.

Example:

ul {
  font:menu; /* Set lists to use a system font. */
  font-style:italic /* Override an individual property. */
}

Text Spacing

[edit | edit source]

text-align

[edit | edit source]

W3C Specification CSS1 CSS2.1

This property is used to justify blocks of text. The four possible values are left, right, center and justify. The values are demonstrated below.

CSS rules:

div {
  width:50% /* Make the column narrower so the alignment is more noticeable. */
}

p {
  border: 1px solid red;
  padding: 1em;
}

#para1 {
  text-align: left;
}

#para2 {
  text-align: right;
}

#para3 {
  text-align: center;
}

#para4 {
  text-align: justify;
}

Sample HTML:

    <div>
      <p id="para1">Web designers and web surfers are divided over the relative merits of left versus
        full justification of text. Many state a preference for left justified text despite the
        fact that most print media is fully justified.
      </p>
      <p id="para2">Web designers and web surfers are divided over the relative merits of left versus
        full justification of text. Many state a preference for left justified text despite the
        fact that most print media is fully justified.
      </p>
      <p id="para3">Web designers and web surfers are divided over the relative merits of left versus
        full justification of text. Many state a preference for left justified text despite the
        fact that most print media is fully justified.
      </p>
      <p id="para4">Web designers and web surfers are divided over the relative merits of left versus
        full justification of text. Many state a preference for left justified text despite the
        fact that most print media is fully justified.
      </p>
    </div>

Example rendering:

Web designers and web surfers are divided over the relative merits of left versus full justification of text. Many state a preference for left justified text despite the fact that most print media is fully justified.

Web designers and web surfers are divided over the relative merits of left versus full justification of text. Many state a preference for left justified text despite the fact that most print media is fully justified.

Web designers and web surfers are divided over the relative merits of left versus full justification of text. Many state a preference for left justified text despite the fact that most print media is fully justified.

Web designers and web surfers are divided over the relative merits of left versus full justification of text. Many state a preference for left justified text despite the fact that most print media is fully justified.

This property interacts with the following other properties:

white-space
If the value of text-align is justify when white-space is pre or pre-line the web browser must treat text-align as being left if the current text direction is left to right (this is the normal for English) or right if the current text direction is right to left.
letter-spacing
If this is set to anything other than normal the web browser may only adjust the inter-word spacing when justifying text.
word-spacing
If this is set to anything other than normal the web browser must try to honor the specified value when justifying text.

letter-spacing

[edit | edit source]

W3C Specification CSS1 CSS2.1

The letter-spacing property is used to increase or decrease the space between letters. Web browsers are not required to support decreasing the letter spacing or may only allow a limited decrease.

The value normal can be used to remove an inherited value from an element. If the value is set to anything other than normal the spacing between letters can not be altered when using text-align to justify the text. You can set letter-spacing to zero if you don't want the letter spacing altered by justification but don't want to add any extra space.

CSS rules:

.increase {
  letter-spacing:0.5em
}

.decrease {
  letter-spacing:-0.05em
}

Sample HTML:

    <p class="increase">Letter spacing.</p>
    <p>Letter spacing.</p>
    <p class="decrease">Letter spacing.</p>

Example rendering:

Letter spacing.

Letter spacing.

Letter spacing.

word-spacing

[edit | edit source]

W3C Specification CSS1 CSS2.1

The word-spacing property is used to increase or decrease the space between words. Web browsers are not required to support decreasing the word spacing or may only allow a limited decrease.

The value normal can be used to remove an inherited value from an element.

CSS rules:

.increase {
  word-spacing:1em
}

.decrease {
  word-spacing:-0.2em
}

Sample HTML:

    <p class="increase">The word spacing can be altered.</p>
    <p>The word spacing can be altered.</p>
    <p class="decrease">The word spacing can be altered.</p>

Example rendering:

The word spacing can be altered.

The word spacing can be altered.

The word spacing can be altered.

Other Text Properties

[edit | edit source]

text-decoration

[edit | edit source]

W3C Specification CSS1 CSS2.1

The text-decoration may either be set to none or any combination of underline, overline, line-through and blink. It is considered bad practice by many web designers to use blink. It is also considered bad practice to underline anything other than a hyperlink. Consider the second and third examples below as examples of what not to do.

If you use line-through to indicate deleted text consider using a semantic element such as (X)HTML's del element either instead of or in combination with this property.

The most common use of text-decoration is to change the appearance of hyperlinks to remove the underline from links in the main content whilst preserving them in navigation menus or vice versa.

CSS rules:

a {
  text-decoration:none
}

li a {
  text-decoration:underline
}

Sample HTML:

    <p>The next chapter is rather boring so all but the most enthusiastic readers
       should skip to <a href="Chapter7.htm">the interesting bit</a>.
    </p>
    <ul>
      <li><a href="Chapter4.htm">Previous</a></li>
      <li><a href="Contents.htm">Contents</a></li>
      <li><a href="Chapter6.htm">Next</a></li>
    </ul>

Example rendering:

The next chapter is rather boring so all but the most enthusiastic readers should skip to the interesting bit.

  • Previous
  • Contents
  • Next

An example of using all four values together. blink is not supported by some browsers so you may be spared that effect.

CSS rule:

#overDone {
  text-decoration:underline overline line-through blink
}

Sample HTML:

    <p id="overDone">Can you actually read this?</p>

Example rendering:

Can you actually read this?

Any text-decoration applied to an element is drawn over all of its content including any child elements, regardless of the value text-decoration set on those elements. Any additional decoration specified for child elements will be applied as well as the parent's decoration.

CSS rule:

.notImportant {
  text-decoration:line-through;
  color:black
}

em {
  text-decoration:none
}

strong {
  text-decoration:underline;
  color:red
}

Sample HTML:

    <p class="notImportant">Most of the text in this sentence is not <em>important</em>.</p>
    <p class="notImportant">The last bit of text in this sentence is
      <strong>very important</strong>.
    </p>

Example rendering:

Most of the text in this sentence is not important.

The last bit of text in this sentence is very important.

Notice that the underlining in the second paragraph is in red, the color assigned to the strong element that is underlined. However, the line through the strong element is black because it belongs to the parent p element, which has its color set to black.

text-indent

[edit | edit source]

W3C Specification CSS1 CSS2.1

The text-indent property specifies the indent for the first line of a block level element. Use margin-left, margin-right, padding-left or padding-right to indent an entire block. The indent may be negative but web browsers are not required to support negative indents or may limit the size of a negative indent. The text-indent property is inherited. In the example below the text-indent is applied to the div elements containing the paragraphs rather than directly to the paragraphs themselves.

Note that the indent is only applied at the start of a block level element. Line breaks caused by inline elements do not cause any additional indents to appear within a block.

CSS rules:

p {
  width:50%;       /* Narrow the column so that there are more
                    * lines of text in the example. */
  margin-left:4em /* Apply a margin to the left of all paragraphs
                    * so there is room for the undent example. */
  margin-top:0.5em /* Separate the two halves of the example slightly. */
}

.indented {
  text-indent:2em;
  border:1px solid red /* Put a border around the first half of the example. */
}

.undented {
  text-indent:-2em;
  border:1px solid blue /* Put a border around the second half of the example. */
}

Sample HTML:

    <div class="indented">
      <p>This paragraph should have an indent similar to that found in novels.
        However there will still be a vertical gap between the paragraphs because that
        is controlled by the <code>margin</code> property. If you want to recreate a novel-like
        appearance you will need to set both properties.
      </p>
      <p>This paragraph has a line break in it, created with the <code>br</code> element.
        Since this doesn't start a new block level element there is no indent or undent after
        the line break.<br> The line break was immediately before this sentence. You may need
        to adjust the width of your browser window to make the line break obvious.
      </p>
    </div>
    <div class="undented">
      <p>This paragraph should have an undent. This is a more unusual style but it can be useful.
        It is most often used with lists to emphasis the start of a list item either instead of 
        or in conjunction with a bullet.
      </p>
      <p>This paragraph has a line break in it, created with the <code>br</code> element.
        Since this doesn't start a new block level element there is no indent or undent after
        the line break.<br> The line break was immediately before this sentence. You may need
        to adjust the width of your browser window to make the line break obvious.
      </p>
    </div>

Example rendering:

This paragraph should have an indent similar to that found in novels. However there will still be a vertical gap between the paragraphs because that is controlled by the margin property. If you want to recreate a novel-like appearance you will need to set both properties.

This paragraph has a line break in it, created with the br element. Since this doesn't start a new block level element there is no indent or undent after the line break.
The line break was immediately before this sentence. You may need to adjust the width of your browser window to make the line break obvious.

This paragraph should have an undent. This is a more unusual style but it can be useful. It is most often used with lists to emphasis the start of a list item either instead of or in conjunction with a bullet.

This paragraph has a line break in it, created with the br element. Since this doesn't start a new block level element there is no indent or undent after the line break.
The line break was immediately before this sentence. You may need to adjust the width of your browser window to make the line break obvious.

text-transform

[edit | edit source]

W3C Specification CSS1 CSS2.1

There are four values for the text-transform property:

none
do nothing.
uppercase
converts any lowercase characters to uppercase. Other characters are unaltered.
lowercase
converts any uppercase characters to lowercase. Other characters are unaltered.
capitalize
converts the first character of each word to uppercase. Other characters are unaltered. In particular uppercase characters elsewhere in a word remain uppercase.

The exact effect of text-transform depends on the language of the element. How the language is determined depends on the document being styled. HTML documents use the lang attribute to specify the language for an element. The language is inherited by child elements unless a lang attribute is used to alter the language. XML documents use xml:lang in the same manner. XHTML 1.0 documents may use either the HTML lang attribute or the XML xml:lang attribute.

Note that copying transformed text to the clipboard may vary throughout browsers. Firefox copies the text to the clipboard as if it were not transformed, and Chrome copies it to clipboard as it appears.

CSS rules:

#para1 {
  text-transform:uppercase
}

#para2 {
  text-transform:lowercase
}

#para3 {
  text-transform:capitalize
}

#para4 {
  text-transform:none
}

Sample HTML:

    <p id="para1">this TEXT is NOT iN aNy PaRtIcULaR CaSe.</p>
    <p id="para2">this TEXT is NOT iN aNy PaRtIcULaR CaSe.</p>
    <p id="para3">this TEXT is NOT iN aNy PaRtIcULaR CaSe.</p>
    <p id="para4">this TEXT is NOT iN aNy PaRtIcULaR CaSe.</p>

Example rendering:

this TEXT is NOT iN aNy PaRtIcULaR CaSe.

this TEXT is NOT iN aNy PaRtIcULaR CaSe.

this TEXT is NOT iN aNy PaRtIcULaR CaSe.

this TEXT is NOT iN aNy PaRtIcULaR CaSe.

Compare the effect of setting text-transform to uppercase with setting font-variant to small-caps.

CSS rules:

.uppercase {
  text-transform:uppercase
}

.small-caps {
  font-variant:small-caps
}

Sample HTML:

    <p>Compare <span class="uppercase">uppercase</span>
      to <span class="small-caps">small-caps</span>.
    </p>

Example rendering:

Compare uppercase to small-caps.

vertical-align

[edit | edit source]

W3C Specification CSS1 CSS2.1

The vertical-align property only applies to elements whose display value is inline or table-cell. The behaviour of vertical-align is significantly different for table-cells and is described in the section on Cascading Style Sheets/Tables.

What not to do

[edit | edit source]

The most common mistake when using vertical-align is to apply it to a block-level element and then wonder why it doesn't work. The following example shows what goes wrong. CSS rules:

div#outer {
  width:100px;
  height:100px;
  background-color:#00f;
  text-align:center
}

div#inner {
  width:50px;
  height:50px;
  background-color:#f00;
  margin:auto;
  vertical-align:middle /* This is ignored because this is a block level element. */
}

Sample HTML:

    <div id="outer">
      <div id="inner">?</div>
    </div>

Example rendering:

?

As you can see the red inner division is firmly aligned with the top of the blue division.

Correct usage

[edit | edit source]

The correct usage of vertical-align is to adjust the relative positions of sections of text and embedded content within a line of text. To understand vertical-align you need to understand CSS line boxes. The following example shows two block-level elements, paragraphs. Each block-level paragraph contains an inline element, span. A border and background are applied to the inline elements so the line boxes are visible.

CSS rules:

p {
  width:20em; /* Narrow the paragraphs to ensure that the second paragraph wraps. */
  font-size:120%;
  line-height:2; /* Increase the line height to make the gaps between lines clearer. */
  border:3px solid red;
  padding:2px;
  background-color:#fcc
}

span {
  background-color:#ddd
  border:3px dashed #060
}

Sample HTML:

    <p><span>This is a short paragraph.</span></p>
    <p><span>This is a much longer paragraph. The text in the paragraph wraps on to
      more than one line. The CSS rendering engine has to split the text into a number
      of line boxes, one for each line of text.</span>
    </p>

This is a short paragraph.

This is a much longer paragraph. The text in the paragraph wraps on to more than one line. The CSS rendering engine has to split the text into a number of line boxes, one for each line of text.

The vertical-align property adjusts the alignment of inline elements relative to other items in the same line box. The next example illustrates how it can be used to create superscripts and subscripts.

CSS rules:

p {
  font-size:150% /* Enlarge the example so it is easier to see. */
}

span {
  font-size:60% /* Superscripts and subscripts are usualy shrunk by about 60%. */
}

.super {
  vertical-align:super
}

.sub {
  vertical-align:sub
}

Sample HTML:

    <p>Text <span>shrunk</span>.</p>
    <p>Text <span class="super">superscript</span>.</p>
    <p>Text <span class="sub">subscript</span>.</p>

Example rendering:

Text shrunk.

Text superscript.

Text subscript.

The full set of values for vertical-align is:

  • baseline
  • superscript
  • subscript
  • middle
  • text-top
  • text-bottom
  • top
  • bottom

CSS2.1

[edit | edit source]

CSS2.1 also allows the value of vertical-align to be a length or percentage.

white-space

[edit | edit source]

W3C Specification CSS1 CSS2.1

The white-space property controls the handling of whitespace (normal spaces, tabs, form feeds and newlines but not non-breaking spaces or other special spaces). In the absence of CSS, HTML and XML documents are rendered with runs of whitespace replaced by a single whitespace character. Blocks of text are word-wrapped so that the text fits within the width of the containing block. For example, the two paragraphs in the sample HTML below would be rendered in the same way.

    <p>A run of whitespace is normally replaced by a single whitespace character,
       e.g. a run of tabs might be replaced by a one normal space.
    </p>
    <p>A   run   
of whitespace is normally replaced by a single whitespace character,
       e.g. a run of tabs might 
be 
replaced 
by a one normal space.
    </p>

Example rendering:

A run of whitespace is normally replaced by a single whitespace character, e.g. a run of tabs might be replaced by a one normal space.

The white-space property has five values. The value normal specifies that text should be handles as usual for an HTML or XML document. The table below shows how the other values compare to normal rendering.

Value Replace runs of whitespace Wrap text to fit the container Start newlines at newlines in the source
normal Replace Wrap No
pre Preserve Overflow Yes
nowrap Replace Overflow No
pre-wrap CSS2.1 Preserve Wrap Yes
pre-line CSS2.1 Replace Wrap Yes

The two values added in CSS2.1, pre-wrap and pre-line, aren't widely supported at the moment.

Internet Explorer for Windows versions 5.0 and 5.5 does not support pre. IE/win v6.0 only supports pre in standards mode.

The HTML pre element behaves as though the following CSS rule is applied.

pre {
  white-space:pre;
  font-family:monospace
}

The example below compares normal and nowrap.

CSS rules:

p {
  width:15em; /* Make the paragraph narrower so wrapping is more obvious. */
  border:1px solid black; /* Highlight the boundary of the paragraph so overflow is more obvious. */
  background:#cfc
}

#para1 {
  white-space:normal
}

#para2 {
  white-space:nowrap
}

Sample HTML:

    <p id="para1">This first sentence.
      The second sentence.
      The third sentence.
    </p>
    <p id="para2">This first sentence.
      The second sentence.
      The third sentence.
    </p>

This first sentence. The second sentence. The third sentence.

This first sentence. The second sentence. The third sentence.

text-shadow

[edit | edit source]

Text shadow is a new effect that is part of CSS3. It's arguments are the same as box-shadow's and supports multiple shadows.

  • text-shadow: x-offset y-offset blur/diffusion color [, repeat for multiple];
p {
   text-shadow: 4px 4px 4px black;
   font-size: x-large;
}

Text with Shadow! Bold! Italic! Underline! Strike!

p {
   text-shadow: 2px 2px 1px black;
   font-size: x-large;
}

Text with Sharp Shadow! Bold! Italic! Underline! Strike!

Now let's try multiple shadows, note that you must keep moving the shadows to prevent them from all being drawn in the same place (unless that is what you want ;) ):

p {
   text-shadow: 2px 2px 2px red, 4px 4px 2px blue, 6px 6px 2px green;
   font-size: x-large;
}

Text with Many Shadows! Bold! Italic! Underline! Strike!

anaglyphs

[edit | edit source]

You can use text-shadow to generate three-dimensional (stereoscopic) red-cyan anaglyphic text.

.anaglyph1 { color: rgba(0,0,0,0); text-shadow: -1px 0px 0px red, 1px 0px 0px aqua; }
.anaglyph2 { color: rgba(0,0,0,0); text-shadow: -2px 0px 0px red, 2px 0px 0px aqua; }
.anaglyph3 { color: rgba(0,0,0,0); text-shadow: -3px 0px 0px red, 3px 0px 0px aqua; }

"color: rgba(0,0,0,0)" makes the un-shadowed text transparent, so that only the red (red) and cyan (aqua) shadows are visible. Note that the cyan shadow is called "aqua" in CSS. The number of pixels offset left or right is then the amount of three-dimensional depth, or how far away from the screen that the text will appear to float. You should only need a small number of pixels. Also know that with red-cyan anaglyphic text, you will not be able to use red or aqua for hyperlink or background colors.

This text has two pixels of red-cyan separation.

This text has four pixels of red-cyan separation.

This text has six pixels of red-cyan separation.

You will need to be wearing red-cyan 3D glasses in order to see the 3D text. Since most visitors to a website will not be wearing 3D glasses, make sure that a non-anaglyphic version of the text is accessible.

Web Fonts

[edit | edit source]

Web fonts are a feature of CSS2 that allow a rule to be set to allow an embeddable font in a web page, freeing a designer from having to rely on a subset of fonts that ship with most OSes. Fonts supported by this feature are either TrueType (.ttf) or OpenType (.otf). Web fonts are currently only supported by WebKit (Safari, Shiira, Chrome, et al.). Internet Explorer supports web fonts only with the Embedded Open Type (.eot) format, something unused by any other browser.

Sample CSS:

@font-face {
   font-family: WikiFont;
   src: url('wikifont.otf');
}

@font-face {
   font-family: WikiFont;
   font-weight: bold;
   src: url('wikifont-bold.otf');
}

@font-face {
   font-family: WikiFont;
   font-style: italic;
   src: url('wikifont-italic.otf');
}

Now, to use the font we simply go about business as usual:

h1, h2, h3, h4, h5, h6 {
   font-family: WikiFont;
}

Then any headings in that document would display in our example "WikiFont" in a supporting browser.