0

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?

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
  • 1
    Check this duplicate question: http://stackoverflow.com/questions/79461/vertical-alignment-of-elements-in-a-div – SVS Jul 04 '12 at 17:12

2 Answers2

6

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/

Ry-
  • 218,210
  • 55
  • 464
  • 476
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
1

I find it easiest to use display:table-cell; vertical-align:middle; here's a jsfiddle

<style>
.a {
    border:1px solid red;
    width:400px;
    height:300px;
    display:table-cell;
    vertical-align:middle;
}
</style>
<div class="a">
    <div>CENTERED</div>
</div>
​
potench
  • 3,802
  • 1
  • 28
  • 39