Dynamically Center Div Within Div

Dynamically Center Div Within Div turned out to be a bit harder to accomplish with CSS than I wanted. I had to handle a case with internationalization where a div with text was contained in a div and need to be centered vertically. The catch was that the text could be from one line to multiple lines. This was the solution I found.

Html Code:

<div id="page">
 <div id="content_container">
   <div id="content">
     <p>your contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour contentyour content</p>
   </div>
 </div>
</div>

Css Code:

#content-outer {
 display:table;
 overflow:hidden;
 margin:0px auto; 
 height:100%;
 width:465px;
}

#content-inner {
 display:table-cell;
 vertical-align: middle;
}

html, body {
 height:100%;
}

Jsfiddle Here

If anyone has a better solution for dynamically vertically centering a div within a div I would love to hear it.

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile