28. Font Size and Scaling (font-size)
The font-size property controls the size of the text within an element. Choosing the right units is crucial for accessibility.
Recommended Practice: rem for Font Size
While you can use pixels for font size, rem units are preferred because they respect the user's default browser settings. If a user increases their default font size for accessibility, rem-based fonts will scale correctly, whereas px fonts will not.
css /* Base font size (optional, but good practice) / html { font-size: 100%; / Default is usually 16px */ }
/* 1.5 times the root font size (16px * 1.5 = 24px) */ h1 { font-size: 1.5rem; }
/* Standard body text size */ p { font-size: 1rem; }
Relative Keywords
CSS also offers relative sizing keywords, often useful for fine-tuning text sizes relative to their parent container:
largersmallerxx-smalltoxx-large
css .caption { /* Font size is relative to the parent element's font size */ font-size: smaller; }
Responsive Font Sizing
To make text scale beautifully with the viewport, you can use vw or combine units using the clamp() function (covered later), but for simple scaling, rem is the foundation.