Align anything vertically or horizontally centered with CSS3.

Mahbub Hasan
2 min readSep 21, 2016

--

Aligning a content or a group of contents vertically and horizontally centered is a regular need in our everyday work. With the help of CSS3 property transform, we can align a content or a group of contents vertically and horizontally centered very easily.

The CSS3 transform property applies a 2D or 3D transformation to an element which allows us to scale, rotate, skew, translate etc. the elements.

With translate we can move an element anywhere in the page. translateY(y) defines a translation, using only the value for the Y-axis and translateX(x) defines a translation, using only the value for the X-axis.

Code:

.content {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}

To align anything horizontally centered we can use translateX(x).

Code:

.content {
position: relative;
left: 50%;
transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
}

Note: We can use margin-left: auto; margin-right: auto; to align a section horizontally, but not for all cases. Of course, the use of translateX(x) is for special cases.

And, to align anything vertically and horizontally centered we can use translate(x,y).

Code:

.content {
position: relative;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}

Sometimes, when we use CSS3 transform property, the transformed element may look little blurry or pixelated on mouse hover or on normal state. To get rid of that issue we can use transform-style: preserve-3d; to the parent.

Code:

.parent {
-webkit-transform-style: preserve-3d;
-ms-transform-style: preserve-3d;
transform-style: preserve-3d;
}

Happy Coding!!!

--

--