Skip to content

Instantly share code, notes, and snippets.

@tankbar
Created February 20, 2018 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tankbar/c5dbb5f55fa9a01677ed92e29254a93a to your computer and use it in GitHub Desktop.
Save tankbar/c5dbb5f55fa9a01677ed92e29254a93a to your computer and use it in GitHub Desktop.
Center a div/element within a div
@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%);
}
}
<div class=“parent”>
<div class=“child both”>I’m centered on both axis!</div>
</div>
<div class=“parent”>
<div class=“child horizontal”>I’m centered horizontally!</div>
</div>
<div class=“parent”>
<div class=“child vertical”>I’m centered vertically!</div>
</div>
.parent {
position: relative;
}
.child {
&.both {
@include centerer;
}
&.horizontal {
@include centerer(true, false);
}
&.vertical {
@include centerer(false, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment