[英]Vertically center unknown height div with scrolling content
我正在尝试制作一个类似灯箱的窗口,该窗口具有一个已知高度的标题栏和一个未知高度的内容区域。
我正在使用一个带有vertical-align: middle
的浮动伪元素vertical-align: middle
到垂直居中。 当窗口的高度小于视口的高度时,这可以完美地工作。
(来自CSS技巧的复制粘贴代码)
/* This parent can be any width and height */
.block {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}
我的问题是,当滚动内容变得比视口高时,我不知道如何限制窗口高度并保持垂直居中。
如果窗口没有标题栏和内部内容区域,则可以通过将max-height
和overflow: auto
应用于窗口元素来轻松实现。 但是我想要一个标题栏,并且我希望滚动条只出现在窗口的内容区域中,如下图所示:
我可以在内容区域设置overflow: auto
,但是以百分比设置的max-height
(我需要,因为我不能假设用户的视口高度)似乎被忽略了。
不使用JS可以进行这种布局吗?
这是一个演示 。 窗口在视口下方溢出,尽管如果您删除了足够的内容(使其比视口更短),则它将垂直居中。
给出bg
height:100%;
并为window
所需的百分比高度更新的演示
.bg {
position: fixed;
top: 0; bottom: 0; left: 0; right: 0;
background: rgba(0,0,0,0.5);
text-align: center;
height:100%; /* The important part you were missing */
}
.window {
vertical-align: middle;
display: inline-block;
position: relative;
height:75%; /* The height you desire */
}
.bg:before {
content: '';
height: 100%;
vertical-align: middle;
display: inline-block;
}
.titlebar {
height: 30px; /* arbitrary value but height is known and static */
position: absolute;
left: 0; right: 0;
}
.window .content {
margin-top: 30px; /* same abritrary value as titlebar height */
height:calc(100% - 60px); /* I would think that this would be 30px,
but in practice it needed 60px... */
overflow:auto;
}
附带说明一下,您应该将所有CSS包含在演示中的同一位置,我困惑于为什么我的方法无法正常工作,直到我注意到演示的最底部添加了填充
编辑
显然,要在纯CSS中完成您想做的事情是不可能的,因为除了auto
之外,您还必须给window
指定一个height
。 因此,我添加了一行javascript,它的工作方式完全符合您的要求
document.getElementsByClassName('window')[0].style.height =
document.getElementsByClassName('window')[0].offsetHeight + "px";
!important
在任何元素中都可以解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.