Kodokon kodokon.com

Text and fonts

Pick a font with font-family, then adjust the size, weight and line spacing for text that is pleasant to read.

9 min · 3 questions

Open this lesson in Kodokon

A font is the design of the letters: Arial, Georgia or Times New Roman are fonts. In CSS, the font-family property chooses the font of a piece of text. You give it a list of fonts separated by commas: the browser tries the first one; if it is not installed on the visitor's device, it moves on to the next, and so on. It's a plan A, a plan B, a plan C.

CSS
body {
  font-family: Georgia, "Times New Roman", serif;
}
Three choices: Georgia, otherwise Times New Roman, otherwise serif.

The last word in the list is a generic family: serif means fonts with serifs (the little feet at the ends of the letters, like in a printed newspaper), sans-serif means fonts without serifs (more modern-looking, like Arial), and monospace means fixed-width fonts where every letter is the same width (ideal for code). Note the quotes around "Times New Roman": they are required whenever a font name contains spaces.

The text size is set with font-size. You already know pixels (16px is the browsers' default size). There is also the rem unit: 1rem equals the page's base size, so 1.5rem is one and a half times that size. The weight, meaning how thick the strokes of the letters are, is set with font-weight: normal for regular text, bold for bold, or a number from 100 (very thin) to 900 (very thick), where 400 is the equivalent of normal and 700 that of bold.

CSS
h1 {
  font-size: 2rem;
  font-weight: 700;
}

p {
  font-size: 16px;
  font-weight: normal;
}
A heading twice as large as the body text, and bold.

One last setting, often overlooked yet essential for comfortable reading: line-height, the line height. It controls the vertical space between the lines of a paragraph. Too tight, and the lines feel suffocating; too loose, and the eye gets lost. Best practice is a unitless value, which multiplies the text size: line-height: 1.5; makes each line one and a half times the font size tall.

CSS
p {
  font-size: 16px;
  line-height: 1.5;
}
Each line is 16 x 1.5 = 24 pixels tall.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Why do you give font-family several fonts, separated by commas?
    • To mix fonts within a single word
    • So the browser tries the next one if a font is missing
    • Because CSS syntax requires at least three values
  2. Which font-weight value corresponds to classic bold (bold)?
    • 100
    • 400
    • 700
    • 900
  3. With font-size: 20px and line-height: 1.5, how tall is each line?
    • 20 pixels
    • 25 pixels
    • 30 pixels
    • 35 pixels