将一个 div 垂直居中对齐到另一个 div 内
假设我的
<div id ="outer" class="outer">
<div id= "inner" class="inner">
//some stuff
</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);
如果其他人正在寻找同一问题的解决方案,这对我有用。
强调文字
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试一下 http://jsfiddle.net/gLChk/12/
但不支持在 IE<8 浏览器中。为了使其在所有浏览器上工作,您必须编写一个 js 来查找 .inner 的高度并应用这些 css 属性
希望这会有所帮助。 :)
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
Hope this helps. :)
尝试一下
jsfiddle
问候
Try it with
jsfiddle
greets
使用:
use: