Centering HTML elements on a web page seems like it should be simple. In some cases, it is… but complex layouts often eliminate some solutions, leaving web developers working without a net.
Centering elements horizontally on the page tends to be easiest, with vertical alignment harder to pull off, and combining the two the most difficult of all. In the age of responsive design, we rarely know the explicit height or width of elements, eliminating many possibilities. To my count, that leaves at least six centering methods in CSS. I’ll start from the simplest and best supported and move to the most complex, working from the same basic code:
This doesn’t align the image vertically: you’d need to add padding to the <div> or margin-top and margin-bottom to its content to achieve that, leaving the container to gain its height from its content.
Centering with margin: auto
Again primarily for horizontal centering, with the same limitations as the text-alignment method above:
Note the display: block, necessary in this case for the image to accept margin: 0 auto.
Uses display: table-cell, rather than actual table markup; allows for both horizontal and vertical centering. Typically requires the addition and manipulation of a second, exterior element, which could be anything from a div to the body itself.
Note that the width: 100% is required to stop the div from collapsing, and that the outer container will require some height in order to vertically center the content. Trying to vertically center the element in the body will also involve the standard trick of setting the html and body height. Works in all browsers, including IE8+.
A technique recently promoted by Stephen Shaw has very good support across browsers. The one downside is that some form of height must be declared for the outer container:
In many respects flexbox is the simplest solution, but one that is held back by the variety of older syntaxes and lack of support in earlier versions of IE (although display: table-cell makes for an acceptable fallback).
Very simply, calc allows you to do calculations based on the current layout of the page. In the simple calculations above, 50% is the halfway point in the container element, but using that alone would set the top left corner of the image to the center of the <div>. We need to bring that position back by half the width and half the height of the image. Expressing that in a longer form: