Centering Mixin

0
0

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;
}

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%);
  }
}

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.