30. Line Height and Vertical Spacing (line-height)
line-height controls the vertical spacing between lines of text, also known as leading. Proper line height is essential for comfortable reading.
Understanding Line Height Values
line-height can take several types of values, but one is strongly preferred.
1. Unitless Number (Recommended)
Using a number (e.g., 1.5) is the best practice. The actual height is calculated by multiplying this number by the element's font-size. This value is inherited by children as a ratio, not a fixed pixel value, ensuring proportionality.
css body { /* Recommended for body text, typically 1.4 to 1.6 for readability */ line-height: 1.6; }
2. Length Units (Avoid for Text)
Using px or rem sets a fixed height, which is problematic because if the font size changes (e.g., in a child element), the fixed line height might cause text overlap.
css /* Avoid: If the font gets large, the 20px line height might be too small */ p { line-height: 20px; }
3. Percentage (Relative to Element's Font Size)
line-height: 150% is equivalent to line-height: 1.5.
Line Height for Centering Single Lines
A practical trick is to use line-height equal to the element's height to vertically center a single line of text, like in a small button or navigation item.
css .nav-item { height: 40px; line-height: 40px; /* Vertically centers the text */ border: 1px solid black; }