CSS Text Alignment: Controlling Typography
Mastering text alignment goes beyond just centering a paragraph. It involves understanding horizontal flow, vertical rhythm, line heights, and how inline elements interact with their containers.
Horizontal Alignment: text-align
The text-align property is your primary tool for horizontal alignment. It applies to block-level elements but affects the inline content inside them.
left: Aligns text to the left margin (default in LTR languages).right: Aligns text to the right margin.center: Centers the text horizontally within the block.justify: Stretches the lines so that both left and right edges are aligned.
The Mystery of vertical-align
Many developers try to use vertical-align: middle on a div and wonder why it doesn't work. The key is that vertical-align only applies to inline, inline-block, or table-cell elements.
It is used to align an inline element relative to the line-height of its parent or sibling elements. For example, aligning a small icon perfectly with adjacent text. If you want to vertically center a block element, you should look into Flexbox (align-items: center) instead!
Vertical Rhythm: line-height
The line-height property sets the distance between lines of text. A crucial best practice is to use unitless values (like 1.5 instead of 24px).
Using a unitless value ensures that child elements recalculate their line-height based on their own font-size, preventing overlapping text issues down the DOM tree.
View Classic Centering Trick+
The Line-Height Trick: Before Flexbox existed, a common way to vertically center a single line of text within a button or div was to set the line-height equal to the element's height..btn { height: 40px; line-height: 40px; }
❓ Frequently Asked Questions
Why isn't vertical-align working on my div?
vertical-align is mathematically designed to work only within an inline formatting context (inline or inline-block elements) or in table cells (table-cell). It has no effect on block-level elements like a standard <div>.
How can I center vertically if vertical-align doesn't work for divs?
Nowadays, the best way to vertically center content within a block container is to use Flexbox or CSS Grid.
display: flex;
align-items: center; /* Vertical centering */
justify-content: center; /* Horizontal centering */Why is unitless line-height recommended?
If you use line-height: 1.5em; or line-height: 24px;, that fixed value is inherited by child elements. If a child has a very large font-size, the line-height won't grow proportionally and the text will overlap. By using a unitless value (1.5), the browser recalculates the line-height based on the font-size of each individual child.
