Absolute Centering with CSS
If you want to center something horizontally in CSS you have an easy job, just use the text-align: center; when work with inline elements or margin: 0 auto; when using block element. But what’s the deal with the vertical center alignment?
The vertical centering may be tricky to achieve. Over the years we got a lot of unofficial methods from some great developer, but until the Flexbox we had to use some quirks.
In this article we check the non-hacky techniques but if you interested in some more solution see this CSS-Tricks article!
Need a custom and unique e-commerce solution? We are almost sure that WooCommerce worth a try.
Absolute Positioning Solution
The absolute centering technique is one of the clearest solutions. On the child element you set the position value to absolute and the left/top property you set 50%-50% offset. Because the position is calculated from the top left corner, you must pull back the item with the half of its width and height. You can achieve this with the transform: translate(-50%, -50%); or in the case of fix size element you can use negative margin with the correct value.
The using of the transform property you don’t need to know the adjusted item dimensions.
- Problematic to align the overhanging elements, so you have to be careful on smaller viewports.
- Sometimes the rendering can be blurry, mostly in the WebKit browsers. In this case, you can use backface-visibility: hidden; and transform-style: preserve-3d;.
Viewport Relative Solution
We can bypass the position: absolute; with margin: 50vh auto 0;. For the horizontal centering we use the margin-left/margin-right: auto; for the vertically we use the relative vh value. Of course, you have to pull back the item like in the absolute example.
- This method only works if you are positioning to the main viewport.
The best available method is given by the not too old Flexbox layout technique. Unfortunately, the life of the flex wasn’t lovely. There was two version which made the browser support and the learning curve hard. If you’d like to support old browsers with it, you must use a bunch of prefixes and different value names.
For the alignment, you have to set the display property to flex and the justify-content/align-items property to center. The declarations take place in the parent element.
- The old browser support can be tricky.
CSS Grid Solution
I’m sure you heard the buzz about the new layout technique named CSS Grid. It is our first, full method for composing different, truly responsive design.
You can achieve the absolute center position similar to the Flexbox solution. You have to set the display property to grid and specify the row/column width. On the child set the justify-self and align-self to center!
- Of course in the older browser, it won’t work.