Centering an element horizontal & vertical can be achieved with a lot of different ways. A quite popular way is to position the element absolute in the center of the page with transform translate. Here is the way to achieve this:
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Don't forget that we need to set position: relative to the parent element.
There are situations where we want to position an element only horizontal or only vertical or both. SASS can combine all of these options in one simple mixin.
So the scss styles will be:
@mixin center($position) {
position: absolute;
@if $position == both {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@else if $position == vertical {
top: 50%;
transform: translatey(-50%);
}
@else if $position == horizontal {
left: 50%;
transform: translatex(-50%);
}
@else if $position == clear {
top: auto;
left: auto;
transform: translate(0, 0);
}
}
To call the above mixin we just need to include the mixin with the needed center value according to each situation.
// vertical & horizontal
.div {
@include center(both);
}
// horizontal
.div {
@include center(horizontal);
}
// vertical
.div {
@include center(vertical);
}
// none
.div {
@include center(clear);
}
Center(clear) also needed in situation that we need to override our values to their default state. A clear & easy way to use, enjoy!
You can see the above mixin in action in the following pen, have fun!
See the Pen Absolute center vertical and horizontal mixin by Vangel Tzo (@srekoble) on CodePen.