1. Flexbox (the modern default)
Give the container a height so there is room to center inside.
.box {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal too, if you want it */
min-height: 200px;
}
The align-items: center line does the vertical work; add justify-content: center to center horizontally as well.
2. A single line of text with line-height
If you only have one line, match line-height to the container height.
.box {
height: 60px;
line-height: 60px;
}
This is a classic trick for buttons and badges, but it only works cleanly when the text never wraps to a second line.
3. CSS Grid in one declaration
.box {
display: grid;
place-items: center;
min-height: 200px;
}
place-items: center centers the text both vertically and horizontally with a single property.
Which method should you use?
- Flexbox — the everyday choice for any block of text.
- line-height — quickest for a single line, like a button label.
- Grid — shortest code when you want both axes centered.
Frequently asked questions
Why is my text not centering vertically?
Almost always because the container has no height. A flex or grid box only has vertical space to work with if it is tall enough, so set a height or min-height on the parent.
Does line-height work for multiple lines?
No. Matching line-height to the height only centers a single line. For wrapping text, use Flexbox or Grid instead.
Want to understand the layout properties behind this? Work through our free HTML & CSS course.