Centering
You might say
Can you center this box both horizontally and vertically? Why is that always so hard?
Align an element to the middle of the available spaceCentering may mean horizontal alignment, vertical alignment, or both. Text can use text alignment, a fixed-width block can use automatic margins, and flexible layouts can use flex or grid. Start by identifying what should be centered inside which container.
When to use it
- Center text inside a heading or button
- Center a fixed-width content column
- Center an empty state in a panel
- Align an item on both axes in a known container
When NOT to use it
- Use absolute offsets without knowing the container size
- Center long body text when left alignment is easier to read
- Add spaces or line breaks until something looks centered
- Apply centering to the whole page when only one child needs it
Anatomy
ElementMain axis: justify-content: centerCross axis: align-items: center
Set display: flex on the parent so it controls how its children are aligned.
The child element being centered
justify-content: center aligns the child along the main axis.
align-items: center aligns the child along the cross axis.
Variants
Flex
The most commonly used centering method in ordinary containers
Grid
It is most economical when the parent element is already grid
Absolute
It’s common in old codes, just recognize it
Typical use cases
Empty state
Login Vibe
Dialog content
No favorites yet
Go shopping and collect your favorite components
Login panel
New feature available
Write the front end like chat
Describe the effect you want and leave the rest to AI
Loading indicator
Further reading