Gerillass

v2.1.0

Center

Type: Mixin
@include center();

* You can call mixins with or without the gls- namespace (e.g. @include gls-center();).

The Center Sass mixin allows you to center elements (those with a position value of either absolute or fixed) on both the horizontal and vertical axes.

Arguments

NameTypeDescription
$axisstringSets the axis of the alignment. Accepts the values horizontal, vertical, and both. The default value is both.

Pass the both value to center an element on both the horizontal and vertical axes, or pass nothing at all.

Examples

Simply call the mixin without passing any arguments to center the selected element on both the horizontal and vertical axes.

Sass
.parent-element {
  position: relative;
  .element{
    position: absolute;
    @include center;
  }
}
CSS
.parent-element {
  position: relative;
}
.parent-element .element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
Result

Let's center the selected element on the horizontal axis only.

Sass
.parent-element {
  position: relative;
  .element{
    position: absolute;
    @include center(horizontal);
  }
}
CSS
.parent-element {
  position: relative;
}
.parent-element .element {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
Result

Now let's center the selected element on the vertical axis only.

Sass
.parent-element {
  position: relative;
  .element{
    position: absolute;
    @include center(vertical);
  }
}
CSS
.parent-element {
  position: relative;
}
.parent-element .element {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Result

Now let's pass the both value to center the selected element on both the horizontal and vertical axes.

Sass
.parent-element {
  position: relative;
  .element{
    position: absolute;
    @include center(both);
  }
}
CSS
.parent-element {
  position: relative;
}
.parent-element .element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
Result