Layout Beginner

Centering elements without the transform hack

The old absolute + transform centering trick took 5 declarations across 2 selectors. Grid does it in 2 properties on the parent.

2 lines
1.parent {
2  display: grid;
3  place-items: center;
4}

5/* No child styles needed. */
Old 7 lines
1.parent {
2  position: relative;
3}
4
5.child {
6  position: absolute;
7  top: 50%;
8  left: 50%;
9  transform: translate(-50%, -50%);
10}
Widely available Since 2020 96% global usage

This feature is well established and works across many devices and browser versions. It has been available across browsers since 2020.

57+
52+
10.1+
16+
display: grid + place-items: center
.parent
✦
place-items: center
Kinsta

Your first month is free

Managed WordPress hosting for faster sites.

Learn more
⚑

Less code

2 properties on the parent vs. 5+ across two selectors. Fewer rules, fewer bugs.

✦

Stays in flow

No position: absolute means the child stays in document flow. Layout stays predictable.

∞

Works on anything

Text, images, divs, forms, anything gets centered. No need to know dimensions.

Lines Saved
7 β†’ 2
71% less code
Old Approach
2 selectors
Parent + child rules
Modern Approach
1 selector
Parent only

How it works

The old approach requires position: relative on the parent and position: absolute + top: 50%; left: 50%; transform: translate(-50%, -50%) on the child. That's 5 declarations across 2 selectors, and the child gets pulled out of normal flow.

The modern approach uses display: grid on the parent and place-items: center, a shorthand for align-items + justify-items. The child stays in flow, and you don't touch the child's styles at all.

New CSS drops.

Join 600+ readers who've survived clearfix hacks.

ESC