Centering Mixin

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Assuming the parent element has position: relative;, these four properties will center a child element both horizontally and vertically inside, no matter what the width of height of either are.

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

See the Pen Centerer Mixin by Chris Coyier (@chriscoyier) on CodePen.

Although beware if the child element being centered is taller than parent, the top could get cut off.

Fancier

If you want to be able to center in only one direction…

@mixin centerer($horizontal: true, $vertical: true) {
  position: absolute;
  @if ($horizontal and $vertical) {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  } @else if ($horizontal) {
    left: 50%;
    transform: translate(-50%, 0);
  } @else if ($vertical) {
    top: 50%;
    transform: translate(0, -50%);
  }
}

See the Pen yybgZd by Chris Coyier (@chriscoyier) on CodePen.