Explain Codes LogoExplain Codes Logo

How to vertically center text in a <span>?

css
responsive-design
best-practices
flexbox
Anton ShumikhinbyAnton Shumikhin·Nov 13, 2024
TLDR

Use display: flex; and align-items: center; for vertical centering in a Flexbox context:

<div style="display: flex; align-items: center; height: 50px;"> <span>Centered Text</span> </div>

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>, introduce align-items: center; to a display: inline-flex; for modern vertical centering.
  • Display: grid: For an alternative modern solution, align-items: center; along with display: grid; could be used.
  • Display: table-cell: Use display: table-cell; and pair it with vertical-align: middle; for legacy browser compatibility.
  • Line-height: For a single line, line-height set equal to the min-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:

span { display: inline-flex; align-items: center; min-height: 45px; /* Adequate min-height */ }

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:

span { border: 1px solid; /* Temporary debugging border, discard before shipping! */ }

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.