Absolutely Center Element within Parent with CSS Transform
Sometimes it is necessary to absolutely center-position (horizontally and vertically) an element within its parent, regardless of the width or height of either.
by prince bazawule
September 13, 2017
HTML
<div class="parent">
<div class="element">
I'm bang in the center!
</div>
</div>
SCSS
/* variables */
/* colours */
$grey: rgba(220, 231, 235, 1);
$lightgrey: rgba(220, 231, 235, 0.25);
$blue: rgba(34, 190, 198, 1);
$white: rgba(255, 255, 255, 1);
/* fonts */
$sans: 'Ubuntu', sans-serif;
$heading: 'Source Sans Pro', sans-serif;
body {
background: $grey;
font-family: 'Ubuntu', sans-serif;
color: $white;
}
/* parent */
.parent {
position: relative;
background: $grey;
width: 100%;
height: 100vh;
}
/* class to center element */
.center-me {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* element to be centered */
.element {
@extend .center-me;
background: $blue;
padding: 5%;
}