How to vertically center text in a <span>
?
Use display: flex;
and align-items: center;
for vertical centering in a Flexbox context:
This flex layout quickly centers the text vertically in a 50px-tall container.
Understanding vertical alignment in CSS
Depending on the environment and the content, different alignment strategies can be leveraged. Here is how you can choose the appropriate one:
- Display: inline-flex: For inline-level
<span>
, introducealign-items: center;
to adisplay: inline-flex;
for modern vertical centering. - Display: grid: For an alternative modern solution,
align-items: center;
along withdisplay: grid;
could be used. - Display: table-cell: Use
display: table-cell;
and pair it withvertical-align: middle;
for legacy browser compatibility. - Line-height: For a single line,
line-height
set equal to themin-height
provides a simple solution.
Each comes with its own strengths and use cases with flexbox and grid becoming increasingly popular due to their modern browser support.
Advanced techniques and tricks
Setting min-height
min-height
ensures that your span scales effectively, maintaining adequate dimensions. For instance:
Cross-browser compatibility
To handle variation in browser rendering, use tools like autoprefixer. Don't forget to verify on caniuse.com to avoid surprise! moments on older browsers.
Debug: Use of borders
A temporary border
can be used to visually assert the alignment:
Choosing between block and inline elements
Inline-block for line-height
When using line-height
for vertical alignment in <span>
, remember to switch the display to inline-block
. This allows line-height
to work as expected.
Flexbox or grid
Both flexbox and grid offer reliable ways to center your content. Flexbox is ideal for 1D layout, while grid excels in 2D layout contexts.
Handling legacy browsers
Internet Explorer consideration
For our good pal IE9, combine display: table-cell;
with vertical-align: middle;
. Don't forget to use prefixes for flexbox support in IE10.
Visually verifying layouts
Ensure your alignment work is visually verified. Relying on code alone is a bit like trusting your dog to guard your sandwich.
Keeping design simple
The more complex the design, the harder it is to implement vertical centering. A simple design helps keep your centering efficient and consistent.
Was this article helpful?