问题
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
回答1:
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. :)
回答2:
.outer {
display: table;
position: relative;
width:100%;
height:200px;
border:1px red solid;
}
.inner {
display: table-cell;
position: relative;
vertical-align: middle;
}
回答3:
Try it with
.inner {
top: 50%;
bottom: 50%;
}
jsfiddle
greets
回答4:
use:
.inner
{
margin-top:auto;
margin-bottom:auto;
}
来源:https://stackoverflow.com/questions/9307566/vertically-center-align-a-div-within-anothe-div