The aim of this article is to show how, with a few CSS tricks, any div can be centered, horizontally and/or vertically. And within the page, a div or any element.
See the Pen Centering a div in a page, basic by Steve Pear () on CodePen.
auto
in the margin
property sets the left and right margins to the available space within the page. The thing to remember is your centered div must have a width
property.
See the Pen Centering a div within a div, old-school by Steve Pear () on CodePen.
width
property.
See the Pen Centering a div within a div with inline-block by Steve Pear () on CodePen.
text-align
property only works on inline elements. The inline-block
value displays the inner div as an inline element as well as a block, so the text-align
property in the outer div centers the inner div.
See the Pen Centering a div within a div, horizontally and vertically by Steve Pear () on CodePen.
width
and height
property. This doesn't work if the outer div has a fixed height.
transform
to center any content in a div vertically. This method uses an HTML empty element as a container, in this case p
. You can wrap a lot in an empty element.
Transform is supported by Chrome 63+, IE11, Microsoft Edge 16+, Firefox 57+, Safari 11+, iOS Safari 11.2+ and Chrome for Android 62+.
See the Pen Vertical center in a div with transform by Tipue () on CodePen.
perspective
value reduces blurring on high definition displays. You can support older browser releases using vendor prefixes for transform
, such as -webkit-transform
and -ms-transform
. The later will go as low as IE9.
See the Pen Centering a div at the bottom of a page by Steve Pear () on CodePen.
width
property. The gap from the bottom of the page is set in the outer div's bottom
property. You can also center a div at the top of a page, replacing the bottom
property with top
.
See the Pen Centering a div in a page, horizontally and vertically by Steve Pear () on CodePen.
width
and height
property.
See the Pen Centering a div in a page, responsive by Steve Pear () on CodePen.
max-width
property.
See the Pen Centering a div within a div, inner div responsive by Steve Pear () on CodePen.
max-width
property.
See the Pen Centering two responsive divs, side by side by Steve Pear () on CodePen.
inline-block
elements within a centered container. This also uses CSS media queries. When the screen size is less than 600 pixels, the max-width
property of both left and right divs is set to 100%.
Flexbox is supported by Chrome 63+, IE11, Microsoft Edge 16+, Firefox 57+, Safari 11+, iOS Safari 11.2+ and Chrome for Android 62+.