Horizontally aligning a div-element within another div-element can be achived with margin: 0 auto; as long as they both have a width-property other than auto, but this does not apply for vertical alignment.
How can you vertically align a div within another div?
There are a number of different approaches to this, based on various ideas. Given that the element has a fixed height (in px, % or what have you), the best solution I’ve found so far is based on the following principle:
Give the parent div
position: relative;and the child divposition: absolute;, to make the child absolutley positioned in relation to the parent.For the child, set
top,bottom,leftandrightto0. Given that the child also has a fixedwidthandheightthat is less than the size of the parent, this will push the browser into an impossible situation.In comes
margin: auto;on the child, as the browsers savior. The browser can now add enough margin on all sides to let the child-element keep its size, yet still fill out the entire parent as forced bytop,bottom,leftandrightset to0.TADAAA! The element gets vertically and horizontally aligned within the parent.
Markup
CSS
A working example
http://jsfiddle.net/sg3Gw/