CSS Typography and Text Styling
Learning Objectives
- Control font family, size, weight and style.
- Understand line height, letter spacing and word spacing.
- Use web fonts and font fallbacks.
- Control text wrapping, alignment and decoration.
1. Font Family
body {
font-family: Arial, Helvetica, sans-serif;
}
code {
font-family: Consolas, monospace;
}Provide fallback fonts so content remains readable when a preferred font is unavailable.
2. Font Size and Weight
h1 { font-size: 2rem; font-weight: 700; }
p { font-size: 1rem; font-weight: 400; }
strong { font-weight: 700; }Font sizes can use rem, em, px and other supported units. Numeric font weights commonly range from 100 to 900 when the font supports them.
3. Line Height and Spacing
p {
line-height: 1.7;
letter-spacing: 0.02em;
word-spacing: 0.1em;
}Line height controls the height of a line box. A unitless line-height is often useful because it scales with the element's font size.
4. Text Alignment and Decoration
.center { text-align: center; }
.link { text-decoration: underline; }
.uppercase { text-transform: uppercase; }
.indented { text-indent: 2em; }Other useful properties include text-decoration-color, text-decoration-thickness, text-underline-offset, text-shadow and white-space.
5. Text Overflow and Wrapping
.single-line {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.long-words {
overflow-wrap: anywhere;
}
text-overflow: ellipsis normally requires constrained available width and appropriate overflow and white-space behavior. overflow-wrap helps prevent long unbreakable strings from overflowing their container.
6. Web Fonts
@font-face {
font-family: "SiteFont";
src: url("fonts/site-font.woff2") format("woff2");
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
body {
font-family: "SiteFont", Arial, sans-serif;
}Use a valid font file path and accurate metadata. Variable fonts can support a range of weights when declared and supported appropriately. font-display: swap allows fallback text to appear while the web font loads.
7. Responsive Typography
h1 {
font-size: clamp(2rem, 5vw, 4rem);
}
p {
max-width: 70ch;
}Fluid typography can adapt to screen size. The ch unit is based on the width of the zero glyph in the relevant font and is useful as a rough text-measure constraint.