Lesson 26 +10 XP

Alignment & Centering

Alignment & Centering

Centering is a classic CSS rite-of-passage. Here are the three main tools!

1. Center block element horizontally

margin: auto with a set width:

.block {
  width: 300px;
  margin: auto;   /* left & right auto => centered */
}

Block elements (block, inline-block can narrow) use margin:auto.

2. Center text/inline content horizontally

text-align: center:

div {
  text-align: center;
}

3. Vertical centering (flexbox is the honest answer)

Flexbox makes vertical centering trivial:

.parent {
  display: flex;
  justify-content: center;  /* horizontal */
  align-items: center;      /* vertical */
  height: 300px;
}

line-height vertical centering

For a single line inside a fixed-height box:

div {
  height: 100px;
  line-height: 100px;   /* center vertically */
}

absolute + transform trick

When other options fail:

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

TL;DR

  • margin: auto centers a block horizontally.
  • text-align: center centers text.
  • flexbox: justify-content (horiz), align-items (vert).
  • line-height trick for single-line.
  • absolute+translate: last resort but works.