Here is a good solution to make vertically and horizontally center a div inside another div. We also discussed how to individually center a div in a div either horizontally or vertically later in this article.
I assume that you have a fixed width and variable/flexible height content box then below is best all-around solution I could build to vertically and horizontally center a div that works with all major browser including FIrefox, Opera, Safari, Chrome and IE 8+.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | //HTML <div class="outerDiv"> <div class="middleDiv"> <div class="innerDiv"> <h1>The heading</h1> <p>Some dynamic content placed here...</p> </div> </div> </div> //CSS .outerDiv { height: 100%; width: 100%; display: table; position: absolute; } .middleDiv { vertical-align: middle; display: table-cell; } .innerDiv { margin-left: auto; margin-right: auto; width: /*whatever width you want to keep*/; } |
You can use a separate style sheet with following changes to accommodate for IE 7 and older:
1 | <!--[if lte IE 7]><link rel="stylesheet... /><![endif]-->; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | .outerDiv { top: 0; display: inline; } .middleDiv { top: 50%; display: inline; position: relative; } .innerDiv { top: -50%; display: inline; position: relative; } |
Horizontally Center a Div
You can apply the following CSS to make the the inner div horizontally center:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //HTML <div id="outerDiv"> <div id="innerDiv"> <h4>heading here</h4> <p>Content will go here...</p> </div> </div> //CSS .innerDiv { width: /* Specify any width less than or % of containing div margin: 0 auto; } /* If you are targeting IE8+ then below one is better*/ .innerDiv { display: table; margin: 0 auto; } |
Vertically Center a Div
Here is a quick CSS to vertically center a div that works in all browsers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //HTML <div id="outerDiv"> <div id="innerDiv"> <h4>heading here</h4> <p>Content will go here...</p> </div> </div> //CSS .outerDiv { float:left; height:50%; margin-bottom:-120px; } .innerDiv { clear:both; height:240px; position:relative; } |
There are many other ways to vertically and horizontally center a div that suit as per specific requirements. We will discuss about them in upcoming articles.