How do I vertically align something inside a span tag?
To vertically center content within a span
element, use display: inline-block;
and vertical-align: middle;
. Ensure your span
element is given an appropriate height
along with a matching line-height
to nail that sweet spot in the middle.
For designs that are more responsive, display: table-cell
coupled with vertical-align: middle;
can work a treat. Especially when aligning an entire chapter of War and Peace (multiple lines of text).
The single-line stratagem with line-height
The good ol' line-height
trick can come in handy when you need to vertically center a lone ranger (single line of text) inside a span:
'Sir Line-Height' should ideally be as tall as his home, the noble container, ensuring he can perfectly lounge, right in the middle.
Modern times call for Flexbox
In this era of responsive designs, Flexbox emerges as the hero of vertical alignment in modern layouts:
Johnny Flexbox promises you nimble content allocation, not breaking a sweat about the container's height. An absolute dream for responsive web designs.
Practically Applying the Knowledge
Screen Presence of Inline Elements
Got inline elements up your sleeve, like images? Using vertical-align: middle;
with an inline-block
display style, can make your design pop:
Line-Height Pitfalls
Do avoid setting a specific height for your span if you're using line-height for centering. Unless you are into making things complicated. Instead, let containers provide the height, and have the span inherit this.
Multiline Woes
Got a multi-paragraph essay to center? Reset the inner element's line-height to normal and wrap it like a burrito in an inline-block
container:
The Overflow Marathon
For Spartan text on a single line that doesn't understand the concept of "breaks", use white-space: nowrap;
. It's the obedient kid who won't break stuff no matter how much you push:
Battle of the Browsers
Always account for the browser warfront. Vertical alignment can don various disguises on different web browsers, thanks to rendering inconsistencies. Ensure your solution is peacekeeping across all platforms.
Was this article helpful?