Chapter 13 of 33

Text & Fonts

Most of the web is text. Notes, documentation, blogs, product pages — users spend their time reading. Good typography is the single biggest thing that makes a site feel professional and easy to read, and bad typography (tiny text, cramped lines, endless line lengths) makes even great content painful.

In this chapter we cover the CSS properties that control fonts (which typeface, how big, how heavy) and text (alignment, spacing, decoration, wrapping). We will use only fonts already available on the user's device here; loading custom fonts from files is the topic of the next chapter, Web Fonts.


Font Properties vs Text Properties

GroupPropertiesWhat they change
Fontfont-family, font-size, font-weight, font-style, line-height, fontThe glyphs themselves: typeface, size, thickness, slant
Texttext-align, text-decoration, text-transform, letter-spacing, word-spacing, text-indent, white-space, text-overflow, text-wrapHow the glyphs are arranged and decorated

Nearly all of these properties are inherited (as we saw in Specificity, Inheritance & the Cascade). That's why the usual practice is to set the base font once on body and let every element inherit it.

body {
  font-family: system-ui, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  color: #1f2937;
}

font-family and Font Stacks

font-family takes a comma-separated list of fonts, called a font stack. The browser uses the first font in the list that is available, and falls back to the next one if it isn't.

p {
  font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

On Windows this paragraph uses Segoe UI; on Android, Roboto; on a Mac, Helvetica Neue; and if none exist, any sans-serif font. The browser even falls back per character: if the first font has no glyph for a Hindi or emoji character, the next font in the stack that has it is used for that character.

  • Font names containing spaces should be quoted: "Times New Roman".

  • Always end the stack with a generic family so there is always a match.

  • Generic family names are keywords and must not be quoted: "sans-serif" would look for a font literally named "sans-serif".

Generic font families

GenericDescriptionTypical example
serifSmall strokes ("feet") at the ends of lettersTimes New Roman, Georgia
sans-serifClean letters without serifsArial, Helvetica
monospaceEvery character has the same widthConsolas, Courier New
cursiveHandwriting-likeComic Sans MS
fantasyDecorativeImpact, Papyrus
system-uiThe operating system's own UI fontSegoe UI, San Francisco, Roboto

There are a few newer ones too, such as ui-monospace, ui-serif, emoji and math, with varying support. system-ui is very popular because it looks native on every device and needs no download.

code, pre {
  font-family: ui-monospace, Consolas, "Courier New", monospace;
}

font-size

The browser default is 16px. You learned the units in CSS Units; here is how they apply to text:

html  { font-size: 100%; }    /* respect the user's browser setting (usually 16px) */
h1    { font-size: 2.5rem; }  /* 2.5 × root size = 40px by default */
small { font-size: 0.875em; } /* 87.5% of the parent's size */
  • Prefer rem for font sizes. If a user increases the default font size in their browser settings (common for people with low vision), rem-based text scales with it.

  • em and % on font-size are relative to the parent's font size, so they compound in nested elements.

  • Keyword sizes exist (small, medium, large, x-large, ... and the relative smaller/larger) but are less precise.

  • Body text should generally be at least 16px on screens.


font-weight

Weight is the thickness of the strokes, on a scale from 1 to 1000. The traditional values are multiples of 100:

ValueCommon name
100Thin
300Light
400Normal / Regular (normal)
500Medium
600Semi-bold
700Bold (bold)
900Black / Heavy
h1     { font-weight: 800; }
strong { font-weight: bold; }    /* = 700 */
.muted { font-weight: 300; }

A weight only looks different if the font actually has that weight (or is a variable font). If you ask for 600 and the font has only 400 and 700, the browser picks the closest available one using a matching algorithm; if no bold exists at all, it may create a "fake bold" by thickening the regular glyphs, which looks worse than a real bold.

The relative keywords bolder and lighter step from the parent's weight. For example, inside a 400-weight paragraph, bolder computes to 700 (we verified this in Chrome).


font-style

em      { font-style: italic; }
.normal { font-style: normal; }
.slant  { font-style: oblique 10deg; }

italic uses the font's true italic design (often with different letter shapes). oblique is a slanted version of the regular glyphs. If the font has no italic, the browser slants the normal glyphs instead.


line-height

line-height sets the height of each line box. Extra space is shared equally above and below the text, which controls how much breathing room there is between lines.

For body text, a line-height of about 1.4–1.7 is comfortable to read. The browser's normal is usually around 1.2, which feels cramped for paragraphs.

body {
  line-height: 1.6;        /* unitless: 1.6 × the element's own font-size */
}

This is a classic interview question. line-height can be written as a number (1.5), a length (24px, 1.5em) or a percentage (150%). They look the same, but they inherit differently:

  • 1.5em and 150% are converted to a fixed length on the parent, and that length is inherited.

  • A unitless 1.5 is inherited as the number itself, and each child multiplies it by its own font size.

Worked example:

.article    { font-size: 16px; line-height: 1.5em; }
.article h2 { font-size: 32px; }
.article line-height = 1.5 × 16px = 24px   ← computed as a length
h2 inherits 24px, but its text is 32px tall
→ lines (24px) are SHORTER than the text (32px): wrapped lines overlap!

Now with a unitless value:

.article    { font-size: 16px; line-height: 1.5; }
.article h2 { font-size: 32px; }
h2 inherits the number 1.5 → 1.5 × 32px = 48px   ✅ proportional

In Chrome, the computed line-height of the h2 is 24px with 1.5em or 150%, and 48px with plain 1.5. So: use unitless line-height.


The font Shorthand

p {
  font: italic bold 1rem/1.6 Georgia, serif;
  /*    style  weight size/line-height family */
}
  • font-size and font-family are required, and they must come last, in that order.

  • Line height goes right after the size, separated by a slash.

  • Style, weight (and a few others) are optional and go before the size.

  • Anything you leave out is reset — including line-height, which goes back to normal. In our test, a paragraph with line-height: 2 followed by font: italic bold 20px Georgia, serif ended up with line-height: normal.

Because of this resetting behaviour, many developers prefer the individual properties except when setting a complete base font.


Text Colour

Text colour is set with color (not text-color or font-color, which don't exist). Formats are covered in Colors. For readability, keep enough contrast: WCAG recommends at least 4.5:1 between normal-size text and its background (3:1 for large text).


text-align

h1      { text-align: center; }
.price  { text-align: right; }
article { text-align: justify; }
p       { text-align: start; }   /* left in English, right in Arabic/Urdu */

text-align aligns the inline content (text, images, inline elements) inside a block. It does not move the block itself: to centre a fixed-width box, use margin-inline: auto (or margin: 0 auto) from Margin & Padding.

justify stretches spaces so both edges line up. It can create ugly "rivers" of white space in narrow columns, so use it carefully.


text-decoration

text-decoration is a shorthand for line, style, colour and thickness:

a {
  text-decoration: none;                /* remove the default underline */
}

.fancy-link {
  text-decoration: underline wavy #e11d48 2px;   /* line style color thickness */
  text-underline-offset: 4px;                    /* move the underline down */
}

.old-price {
  text-decoration: line-through;
}
Sub-propertyValues
text-decoration-linenone, underline, overline, line-through
text-decoration-stylesolid, double, dotted, dashed, wavy
text-decoration-colorany colour
text-decoration-thicknessa length, or auto / from-font

If you remove the underline from links inside paragraphs, give them another clear visual cue (colour plus bold, or an underline on hover/focus), otherwise users can't tell they are links.


text-transform, letter-spacing, word-spacing, text-indent

.label {
  text-transform: uppercase;    /* also: lowercase, capitalize, none */
  letter-spacing: 0.1em;        /* extra space between characters */
}

.wide-words { word-spacing: 0.5em; }

.book p { text-indent: 2em; }   /* indent the first line of each paragraph */
  • text-transform changes only the display. The HTML still contains the original text, so copy-paste and screen readers may see the original casing. Write content in normal case and transform it in CSS when the uppercase is just a design choice.

  • capitalize uppercases the first letter of each word; it doesn't lowercase the rest.

  • Uppercase text usually needs a little positive letter-spacing to look good. Use em so the spacing scales with the font size.


white-space

By default HTML collapses runs of spaces and newlines into a single space and wraps lines automatically. white-space changes that:

ValueCollapses spaces?Keeps newlines?Wraps long lines?
normalYesNoYes
nowrapYesNoNo
preNoYesNo
pre-wrapNoYesYes
pre-lineYesYesYes

pre is what the <pre> element uses. pre-line is handy for user-typed text like addresses or comments, where line breaks matter but extra spaces don't. (In the newest spec, white-space is a shorthand for white-space-collapse and text-wrap-mode, but the values above remain the usual way to write it.)


Long Words and Overflowing Text

Breaking long words

Browsers only break lines at allowed places such as spaces and (sometimes) hyphens or slashes. A long URL or a 40-character variable name can stick out of a narrow box. Fixes:

.comment {
  overflow-wrap: anywhere;   /* break a long word only if it would overflow */
}

.code-cell {
  word-break: break-all;     /* break between any two letters, even if not needed */
}

article {
  hyphens: auto;             /* hyphenate using a dictionary; needs lang="en" on html */
}

overflow-wrap: break-word is the older, similar value. In Chrome, a 120px box containing a long URL let part of it stick out by default; with overflow-wrap: anywhere the URL wrapped neatly inside the box.

Truncating with an ellipsis

To cut a single line and show "…", you need all four of these:

.title {
  width: 200px;             /* 1. a limited width (or a constrained parent) */
  white-space: nowrap;      /* 2. keep it on one line */
  overflow: hidden;         /* 3. hide what doesn't fit */
  text-overflow: ellipsis;  /* 4. show … at the cut */
}

With the text "This is a very long line of text that will not fit" in the default 16px system font on Windows, Chrome shows (the exact cut point depends on the font):

This is a very long line of t…

text-overflow alone does nothing; it only decides how already-hidden overflow is shown. (overflow itself is explained in Overflow & Scrolling.)


Modern Line Wrapping: text-wrap

h1, h2, h3 {
  text-wrap: balance;   /* make the lines of a heading roughly equal in length */
}

p {
  text-wrap: pretty;    /* avoid a single lonely word on the last line */
}

With normal wrapping, a bold 20px heading like "Learn CSS layout from scratch for placements" in a 300px box breaks as a long first line ("Learn CSS layout from scratch") plus a short "for placements". With balance, Chrome splits it into two lines of similar length ("Learn CSS layout from" / "scratch for placements"), which looks more designed.

ValuePurposeSupport (Nov 2026)
balanceEqual line lengths; for short text like headingsBaseline since 2024 (all major browsers)
prettyBetter paragraph endings (no orphans); slower, for body textChrome/Edge and Safari; not yet Baseline

Both are progressive enhancements: browsers that don't support them just wrap text normally, so they are safe to use.


text-shadow (briefly)

.hero-title {
  text-shadow: 0 2px 4px rgb(0 0 0 / 0.5);   /* x-offset y-offset blur colour */
}

A subtle text shadow can make white text readable over a busy photo. Shadows in detail are covered in Shadows & Filters.


Complete Example: A Readable Article

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Text &amp; Fonts</title>
  <style>
    body {
      font-family: system-ui, "Segoe UI", Roboto, sans-serif;
      font-size: 1.125rem;
      line-height: 1.6;
      color: #1f2937;
      max-width: 65ch;
      margin: 40px auto;
      padding: 0 16px;
    }
    h1 {
      font-family: Georgia, "Times New Roman", serif;
      font-size: 2.5rem;
      line-height: 1.2;
      text-wrap: balance;
    }
    .tag {
      font-size: 0.75rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      color: #6b7280;
    }
    a {
      color: #2563eb;
      text-underline-offset: 3px;
    }
    code {
      font-family: ui-monospace, Consolas, monospace;
      font-size: 0.9em;
    }
  </style>
</head>
<body>
  <p class="tag">Operating Systems</p>
  <h1>Understanding Deadlocks Before Your GATE Exam</h1>
  <p>A deadlock happens when processes wait for each other forever.
     Read about <a href="#">Coffman conditions</a> and use
     <code>wait()</code> carefully.</p>
</body>
</html>

Result: a centred column about 65 characters wide (a comfortable reading length), a small grey uppercase label with spaced-out letters, a large serif heading whose two lines are balanced, and body text in the system font at 18px with relaxed line spacing. The link is blue with its underline sitting a little below the text, and the inline code uses a monospace font.


Common Mistakes

  • Quoting generic families: font-family: "sans-serif" doesn't work as a generic.

  • No generic fallback at the end of a font stack.

  • Line-height with units on a parent: 1.5em is inherited as a fixed length and causes overlapping lines in larger children. Use unitless.

  • The font shorthand resetting things: it resets line-height (and others) you didn't mention.

  • Using text-align: center to centre a box: it centres the content inside, not the box.

  • Expecting text-overflow: ellipsis to work alone: it needs overflow: hidden, white-space: nowrap and a limited width.

  • Typing content in ALL CAPS instead of using text-transform.

  • Font sizes in px everywhere, which ignores the user's preferred default size.


Interview / Exam Questions

1. Why should line-height usually be unitless?

A unitless value is inherited as a ratio, so each element computes its own line height from its own font size. A value like 1.5em or 150% is computed once on the parent and inherited as a fixed length, which can be too small for children with bigger text and makes their lines overlap.

2. What is a font stack and why end it with a generic family?

A font stack is a list of fonts in font-family. The browser uses the first available one (even per character). The generic family at the end (like sans-serif) guarantees a reasonable font is always available.

3. A parent has font-size: 20px; line-height: 150%;. A child has font-size: 40px. What is the child's line-height?

30px. The percentage is computed on the parent (150% × 20px = 30px) and the child inherits that length. With line-height: 1.5 it would be 1.5 × 40 = 60px.

4. What are the required parts of the font shorthand?

font-size and font-family, in that order at the end, e.g. font: 16px Arial, sans-serif;. A line height can follow the size after a slash.

5. Which properties are needed to truncate text with "…"?

A limited width, white-space: nowrap, overflow: hidden and text-overflow: ellipsis.

6. Difference between white-space: pre and pre-wrap?

Both preserve spaces and newlines. pre never wraps long lines (they overflow), while pre-wrap also wraps lines when they reach the edge of the box.

7. What does font-weight: bolder compute to inside text of weight 400?

700. bolder and lighter are relative to the inherited weight.


Summary

PropertyCommon values
font-familysystem-ui, sans-serif
font-size1rem, 1.25rem, 0.875em
font-weight400, 700, bold
font-styleitalic, normal
line-height1.5–1.7 (unitless)
text-alignstart, center, justify
text-decorationnone, underline, line-through
text-transformuppercase, capitalize
white-spacenowrap, pre-wrap, pre-line
text-wrapbalance, pretty
  • Set the base font on body; typography properties inherit.

  • Use font stacks ending in a generic family, rem for sizes, and unitless line-height.

  • Text properties arrange the content inside a box; they don't move the box.

So far we have only used fonts installed on the user's device. In the next chapter, Web Fonts, we will load any font we like with @font-face and Google Fonts.