CSS: Vertically Align Div or Any Block Type Object Inside a Div

This is one of the most common ways to vertically align a div or any block type object within a div. The child object has to be a fixed height for this to work. Only block objects such as div, img or p tags can have a fixed height. You can also make inline type objects such as the span tag into a block object with ‘display: block’ style attribute.

This will work in all modern browsers.

1. The parent div needs to be ‘position: absolute’ or ‘position: relative’.
2. The child block object needs to be position: absolute. Child object will be absolutely positioned within the parent object.
3. Child block object will be positioned half way within parent using top: 50%
4. Will then apply a negative margin that is half the height of child object.

The child object in this case is 40px in height. The css will look something like this:

<style type="text/css">
	#parentDiv { position:relative;height:300;width:300;}
	#childDiv { position:absolute; top:50%; height:40px; margin-top:-20px }

This will position the child block object in the vertical center of the parent div.

Leave a comment