π Introduction
The vertical-align property in CSS controls the vertical alignment of inline-level elements, inline-block elements, table cells, and text fragments relative to the surrounding text baseline. Despite the name, it does NOT vertically center block elements β thatβs a common beginner mistake. It is mainly used for icons inside text, superscripts/subscripts, images in line with text, and table cells. β¨
π― Why Use vertical-align?
- To align inline elements like images with text πΌοΈ
- To adjust icons inside buttons π
- To create superscript/subscript effects easily π’
- To align content inside table cells π
β¨ Syntax
Basic Syntax
selector {
vertical-align: baseline | middle | top | bottom | text-top | text-bottom | sub | super | <length> | <percentage>;
}Note
vertical-align works only on inline,inline-block, or table-cell elements β NOT on block elements.π§© Available Values
1. baseline (default)
The element aligns with the baseline of its parent text.
2. middle
Aligns the middle of the element with the middle of the parentβs x-height.
3. top
Aligns the top of the element with the tallest element in the line.
4. bottom
Aligns the bottom of the element with the lowest element in the line.
5. text-top / text-bottom
Aligns the element with the top or bottom of the parent textβs content area.
6. sub / super
Simulates subscript (sub) and superscript (super) positions β useful for math or chemistry.
7. length or percentage
You can manually shift the element up or down.
Length/Percentage Example
span.icon {
vertical-align: -3px; /* moves element 3px down */
}π₯ Practical Examples
1. Aligning an Icon with Text
Icon Example
.btn img {
vertical-align: middle;
}2. Superscript & Subscript
Super/Sub Example
sup { vertical-align: super; }
sub { vertical-align: sub; }3. Align Inline Image to Top
Top Alignment
img.top-align {
vertical-align: top;
}4. Custom Offset Adjustments
Custom Offset
.adjust {
vertical-align: -5px; /* push down */
}π Comparison Table
| Value | Effect | Best For |
|---|---|---|
| baseline | Aligns with text baseline | Default inline alignment |
| middle | Aligns with text middle | Icons inside text |
| top | Aligns top with tallest element | Inline images |
| bottom | Aligns bottom with lowest item | Mixed content lines |
| super / sub | Moves element up/down like x or x | Math, chemistry, footnotes |
| length / % | Manual vertical adjustment | Fine-tuning alignment |
πΌοΈ Visual Demo
Further details can be found at: https://dummyimage.com/900x260/eeeeee/000000&text=vertical-align+demo
π Conclusion
The vertical-align property is a powerful tool for aligning inline elements, inline-blocks, and table cells. Use middle for icons, super/sub for mathematical text,top/bottom for images, and length values for pixel-perfect control. Remember: it doesn't vertically center block elements β but it's essential for inline layout precision. π