How do I vertically center text with CSS?
Easily center text vertically using Flexbox: set display: flex;
, justify-content: center;
, and align-items: center;
:
Apply to your element:
Perfect for any text amount, adapts seamlessly across devices.
More solutions to vertical centering
Solo Line Centering: lineHeight and textAlign
For single-line text, set the line-height
to match the container's height:
This is your go-to when your container's height is known and the text won't wrap.
Legacy Support: table-cell method
When Flexbox gives you the cold shoulder (older browsers), simulate table behavior:
Ideal for multi-line text and in ensuring compatibility with legacy browsers.
Dynamic Heights: transform technique
When your elements have dynamic heights, go for:
This centers regardless of the container's size - kind of like how some people are the center of attention no matter where they are!
Vertical Stacking: Flexbox column
Want to vertically stack multiple items?
Perfect for creating a column layout where each child is evenly spaced and happily centered.
Cross-browser prefixing: All browsers matter
Include Flexbox vendor prefixes to keep all browsers happy:
Check support on websites like caniuse.com, and use tools like flexyboxes to help you with cross-browser Flexbox styles.
Mixins for code reuse
Create SASS/SCSS mixins to reuse vertical centering styles across projects:
Finer points in styling
Lean on visual styling to add character to your centered element:
The right dimensions and margin are crucial for achieving the perfect look.
Learning by example
Check out online platforms like CodePen and JSFiddle for working examples. Code it, see it live!
Was this article helpful?