Comments:"The Tipue blog - The complete guide to centering a div"
URL:http://www.tipue.com/blog/center-a-div/
text-align
property a value of center
, but then things tend to get a bit sticky. When you get to centering a div vertically, you can end up in a world of CSS hurt.The aim of this article is to show how, with a few CSS tricks, any div can be centered; horizontally, vertically or both. And within the page or a div.
Centering a div in a page, basic
This method works with just about every browser, ever.
CSS
.center-div { margin: 0 auto; width: 100px; }
The value 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.
centering a div within a div, old-school
This works with almost every browser.
CSS
.outer-div { padding: 30px; } .inner-div { margin: 0 auto; width: 100px; }HTML
The margin auto trick strikes again. The inner div must have a width
property.
Centering a div within a div with inline-block
With this method the inner div doesn't require a set width. It works with all reasonably modern browsers, including IE 8.
CSS
.outer-div { padding: 30px; text-align: center; } .inner-div { display: inline-block; padding: 50px; }HTML
The 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.
Centering a div within a div, horizontally and vertically
This uses the margin auto trick to center a div both horizontally and vertically. It works with all modern browsers.
CSS
.outer-div { padding: 30px; } .inner-div { margin: auto; width: 100px; height: 100px; }HTML
The inner div must have a width
and height
property. This doesn't work if the outer div has a fixed height.
Centering a div at the bottom of a page
This uses margin auto and an absolute-positioned outer div. It works with all modern browsers.
CSS
.outer-div { position: absolute; bottom: 70px; width: 100%; } .inner-div { margin: 0 auto; width: 100px; height: 100px; background-color: #ccc; }HTML
The inner div must have a width
property.
Centering a div in a page, horizontally and vertically
This uses margin auto again and an absolute-positioned outer div. It works with all modern browsers.
CSS
.center-div { position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; width: 100px; height: 100px; background-color: #ccc; }
The div must have a width
and height
property.