0

say i have

<div id ="outer" class="outer">
    <div id= "inner" class="inner">
      //some stuff
    </div>
</div>

the inner div has a dynamic height, it changes depending on what is inside the div. the outer div is just a container which is set to have the height of the window.

I want to set it so that the inner div is vertically centered within the outer div. Is there a way to do this easily in CSS or is JavaScript necessary?

THE SOLUTION I FOUND:

var container= document.getElementById("outer");
var inner= document.getElementById("inner");
var inHeight=inner.offsetHeight;

container.style.height=(window.innerHeight-10);
container.style.width=window.innerWidth;

var conHeight=container.offsetHeight;

inner.style.marginTop=((conHeight-inHeight)/2);

In case anyone else searching for a solution to the same problem, this worked for me.

emphasized text

moesef
  • 4,641
  • 16
  • 51
  • 68
  • Related question with some useful suggestions: http://stackoverflow.com/questions/7206640/css-vertically-align-div-when-no-fixed-size-of-the-div-is-known – Artyom Feb 16 '12 at 08:26

4 Answers4

3

try this out http://jsfiddle.net/gLChk/12/

but it won't be supported in IE<8 browsers. To make it work on all the browsers, you'll have to write a js which will find the height of .inner and apply these css properties

$(document).ready(function(){
var inner = $('.inner'),
    ht = inner.height();

inner.css({'position':'absolute','top':'50%','margin':-ht/2+'px 0 0 0'});
});

Hope this helps. :)

Abhidev
  • 7,063
  • 6
  • 21
  • 26
0
.outer {
    display: table;
    position: relative;
    width:100%;
    height:200px;
    border:1px red solid;
}
.inner {
    display: table-cell;
    position: relative;
    vertical-align: middle;
}
Desigens
  • 63
  • 4
-1

Try it with

.inner {
top: 50%;
bottom: 50%;    
}

jsfiddle

greets

CyrillC
  • 557
  • 1
  • 3
  • 15
-3

use:

.inner
{
    margin-top:auto;
    margin-bottom:auto;
}
Hadas
  • 10,188
  • 1
  • 22
  • 31
  • i actually think this will work... but it turns out that my outer div is not set to the height and width of the window.... – moesef Feb 16 '12 at 08:13