The line-height
property in CSS controls the amount of space between lines of text. It is crucial for readability and creating a visually pleasing layout. It can be set using various units, including unitless values, pixels, and percentages.
Example 1: Using a Unitless Value
/* This rule targets all paragraph elements. */
p {
/* It sets the line height to be 1.5 times the font size of the element. */
line-height: 1.5;
}
Explanation
Using a unitless value is the recommended best practice for line-height
as it is relative to the element's font-size
. This ensures that the line height scales appropriately if the font size changes.
Example 2: Using Pixels
/* This rule applies to elements with the class "fixed-line-height". */
.fixed-line-height {
/* It sets a fixed line height of 24 pixels. */
line-height: 24px;
}
Explanation
Setting line-height
in pixels provides a fixed space between lines, which might not be ideal for responsive or accessible designs.
Example 3: Using Percentages
/* This rule targets the body of the document. */
body {
/* The line height will be 150% of the element's font size. */
line-height: 150%;
}
Explanation
Percentages for line-height
are relative to the element's font-size
, similar to em
units.
Example 4: Using the normal
Keyword
/* This rule applies to all list items. */
li {
/* It resets the line height to the browser's default, which is usually around 1.2. */
line-height: normal;
}
Explanation
The normal
keyword sets the line-height
to the browser's default value. The exact value can vary between browsers.
Example 5: Using em
Units
/* This rule targets all blockquote elements. */
blockquote {
/* The line height will be 1.6 times the font size of the blockquote. */
line-height: 1.6em;
}
Explanation
em
units for line-height
are also relative to the element's font-size
. However, unitless values are generally preferred to avoid compounding issues in nested elements.
Example 6: Vertically Centering Single-Line Text
/* This rule targets a button element. */
.button {
height: 50px;
/* By setting the line-height equal to the height, the text inside will be vertically centered. */
line-height: 50px;
}
Explanation
A common technique for vertically centering a single line of text within a container is to set the line-height
equal to the height
of the container.
Example 7: Using rem
Units
/* This rule targets a specific div. */
div {
/* The line height will be 2 times the root font size. */
line-height: 2rem;
}
Explanation
Using rem
units for line-height
bases the line spacing on the root <html>
element's font size, which can help with overall consistency in your design.