To me, best option you have is to use the transform:translate
property.
.object {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
No need ta calculate the width/2
and height/2
margin anymore.
And if you're using SASS
, here is a magic @mixin to use :
@mixin transform($transforms) {
-moz-transform: $transforms;
-o-transform: $transforms;
-ms-transform: $transforms;
-webkit-transform: $transforms;
transform: $transforms;
}
@mixin center($position: "both") {
position: absolute;
@if $position == "vertical" {
top: 50%;
@include transform(translateY(-50%));
}
@if $position == "horizontal" {
left: 50%;
@include transform(translateX(-50%));
}
@if $position == "both" {
top: 50%;
left: 50%;
@include transform(translate(-50%, -50%));
}
}
Then, simply use
.object {
// both vertical and horizontal
@include center;
// only vertical
@include center(vertical);
// only horizontal
@include center(horizontal);
}