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 div position: absolute;
, to make the child absolutley positioned in relation to the parent.
For the child, set top
, bottom
, left
and right
to 0
. Given that the child also has a fixed width
and height
that 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 by top
, bottom
, left
and right
set to 0
.
TADAAA! The element gets vertically and horizontally aligned within the parent.
Markup
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent {
width: 200px;
height: 200px;
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
}
A working example
http://jsfiddle.net/sg3Gw/