Skip to content

Instantly share code, notes, and snippets.

@riapacheco
Last active November 19, 2022 04:44
Show Gist options
  • Save riapacheco/87e085835da02b1aaf8efeb82e68d9cd to your computer and use it in GitHub Desktop.
Save riapacheco/87e085835da02b1aaf8efeb82e68d9cd to your computer and use it in GitHub Desktop.
Centering a DIV with `absolute`
@import '../mixins.scss';
// Variables are easy to use and enable calc() to work with different unit types (px, vh, in, etc)
$container-width: 800px;
$div-width: 20px;
.container {
width: $container-width;
position: relative;
.div-to-center {
width: $div-width;
@include center-absolute( $direction: 'LR', $itemSize: $div-width, $containerSize: $container-width );
}
}
@mixin center-absolute(
$direction,
$itemSize,
$containerSize) {
position: absolute;
@if ( // IF centering the div VERTICALLY
$direction == 'TD' or
$direction == 'top' or
$direction == 'down'
) { // THEN apply absolute START position at HALF length (with HALF of div's length subtracted from it)
top: calc(($containerSize / 2) - ($itemSize / 2));
}
@if ( // IF centering the div HORIZONTALLY
$direction == 'LR' or
$direction == 'left' or
$direction == 'right'
) { // THEN apply absolute START position at HALF length (with HALF of div's length subtracted from it)
left: calc(($containerSize/2) - ($itemSize /2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment