在div中垂直居中对齐div [英] Vertically center align a div within anothe div
问题描述
说我有
< div id =outerclass =outer>
< div id =innerclass =inner>
//一些东西
< / div>
< / div>
内部div具有动态高度,它会根据div内的内容而变化。外部div只是一个容器,它被设置为窗口的高度。
我想要设置它以便内部div在外部div内垂直居中。有没有一种方法可以轻松地在CSS中执行此操作,或者是JavaScript所必需的?
我找到的解决方案:
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);
如果其他人正在寻找相同问题的解决方案,这对我来说很有用。
强调文本
a href =http://jsfiddle.net/gLChk/12/ =nofollow> http://jsfiddle.net/gLChk/12/
但IE< 8浏览器不支持。为了使它在所有浏览器上都能正常工作,必须编写一个js,它将查找.inner的高度并应用这些css属性。
$(document).ready(function(){
var inner = $('。inner'),
ht = inner.height();
inner.css({'position':'absolute','top':'50%','margin': - ht / 2 +'px 0 0 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
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. :)
这篇关于在div中垂直居中对齐div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!