Last active
November 19, 2022 04:44
-
-
Save riapacheco/87e085835da02b1aaf8efeb82e68d9cd to your computer and use it in GitHub Desktop.
Centering a DIV with `absolute`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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