Skip to content

The Ultimate CSS Centering Guide

| snippet

The days of margin: 0 auto hacks are over.

1. Flexbox (The Go-To)

Perfect for centering a single child or a row of items.

.parent {
  display: flex;
  justify-content: center; /* Horizontal */
  align-items: center;     /* Vertical */
}

2. Grid (The Super Short)

The absolute shortest modern way.

.parent {
  display: grid;
  place-items: center;
}

3. Position Absolute (The Classic)

When you need to float something over other content.

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}