Topic 20 of 62
Text Formatting
Overview
Beyond just picking a font and a size, CSS gives you microscopic control over how text flows and renders. Adjusting spacing, capitalization, and alignment is critical for readability. Poorly formatted text (like incredibly long, squished lines of text) causes immense eye strain and causes users to abandon your website.
Syntax
css
p {
/* Line Height (Leading): Space between vertical lines.
ALWAYS use unitless numbers for perfect scaling! */
line-height: 1.6;
/* Letter Spacing (Tracking): Space between characters. */
letter-spacing: -0.02em; /* Negative tracking tightens modern fonts */
/* Word Spacing: Space between words. */
word-spacing: 0.1em;
/* Text Align: left, center, right, or justify */
text-align: left;
}
h1 {
/* Text Transform: uppercase, lowercase, capitalize */
text-transform: uppercase;
/* Text Decoration: underline, line-through, none */
text-decoration: underline;
text-decoration-style: wavy; /* Modern CSS allows styling the underline! */
text-decoration-color: red;
}Common Pitfalls
- Using
pxforline-height(e.g.,line-height: 24px;). If you change the font size to 30px later, the line height remains 24px, causing the lines of text to violently smash and overlap each other. Always use unitless numbers (line-height: 1.5), which act as a multiplier of the current font size. - Using
text-align: justify;on the web without enabling hyphens. Justified text aggressively stretches spacing between words to create perfect square blocks of text. Without hyphenation, this creates massive, ugly 'rivers of white space' flowing through your paragraphs.
Interview Questions
Q:
Why should you never use HTML to type out ALL CAPS (e.g.,
<h1>WELCOME</h1>), but instead use CSS text-transform: uppercase;?A:
If you type it in HTML, some aggressive screen readers will assume it's an acronym and read it out letter by letter ('W-E-L-C-O-M-E'). Typing it normally in HTML and using CSS to transform it visually ensures the screen reader speaks it normally as a word.
Real-World Example
Optimizing text width for maximum reading comfort (The 'Measure').
example
css
/*
Human eyes get tired if a line of text is too long.
The 'ch' unit is exactly the width of the '0' character in the current font.
Limiting paragraphs to ~65ch is the golden rule of typography.
*/
article p {
max-width: 65ch;
line-height: 1.7;
margin-inline: auto; /* Centers the block */
}Check Your Knowledge
Test your understanding of Text Formatting with these quick questions.