Sub topic 3
Font Size, Weight, and Style
Assume you know basic HTML, CSS selectors, the cascade, the box model, and how to link a stylesheet. This chapter focuses on readable text that adapts to user settings.
Font size, weight, and style
font-size controls the height of text. Use rem for most text because it follows the root element's size and respects browser preferences. Use em when a value should scale with the element's own font size.
font-weight controls how heavy text appears. Common values are 400 for normal text and 700 for bold text. font-style usually selects normal or italic.
html {
font-size: 100%;
}
body {
font-size: 1rem;
}
h1 {
font-size: clamp(1.75rem, 1rem + 3vw, 3rem);
font-weight: 700;
font-style: normal;
}
em {
font-style: italic;
}Avoid setting every size in pixels. Fixed values can make text harder to enlarge. Also check that the selected font actually provides the requested weight. Browsers may simulate a weight when it is missing.
Loading custom fonts with `@font-face`
@font-face registers a font file so the browser can use it. Always provide fallback fonts. The browser uses the first available family in the list.
@font-face {
font-family: "Inter";
src: url("/fonts/inter.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
body {
font-family: "Inter", system-ui, sans-serif;
}Declare each weight and style that you ship. Otherwise, the browser may synthesize bold or italic text.
Line height, letter spacing, and word spacing
line-height sets the distance between baselines. A unitless value scales with the element's font size and is usually the safest choice. Body text often works well around 1.5.
letter-spacing changes space between characters. word-spacing changes space between words. Use both sparingly. Excessive spacing can reduce readability.
body {
line-height: 1.5;
}
h1 {
line-height: 1.1;
letter-spacing: -0.02em;
}
.label {
letter-spacing: 0.08em;
word-spacing: 0.1em;
text-transform: uppercase;
}Text alignment, wrapping, and decoration
Use text-align to control horizontal alignment. Use overflow-wrap: anywhere for long URLs or identifiers that must fit narrow containers. Use text-decoration for links and other semantic emphasis.
.article {
max-width: 65ch;
text-align: start;
overflow-wrap: anywhere;
}
a {
text-decoration: underline;
text-decoration-thickness: 0.1em;
text-underline-offset: 0.15em;
}Do not remove underlines from links without another clear visual cue. Avoid text-align: justify for most web content because it can create uneven gaps.
Exercise
Which unit is usually the best default for body font size, and why?
Show answer
Use rem because it follows the root font size and respects user browser settings.