[英]Centrally aligned, scrollable div in fixed container
I'm struggling to centrally align a div
within a div
with position:fixed
(I need it fixed as this UI will float over the rest of an existing page). 我正在努力将
div
中的div
与position:fixed
集中对齐(我需要对其进行修复,因为此UI会浮动在现有页面的其余部分上)。 The central div
will contain a considerable amount of content so needs to scroll vertically. 中央
div
将包含大量内容,因此需要垂直滚动。 It also needs to scale horizontally with respect to the viewport with a maxwidth. 它还需要相对于具有最大宽度的视口水平缩放。
Here's what I have so far - it is almost there - just can't work out how to centralise the yellow div
. 这就是我到目前为止所拥有的-几乎已经存在了-只是想不出如何集中黄色
div
。
http://jsfiddle.net/p7F3u/ http://jsfiddle.net/p7F3u/
EDIT I need to support IE9, FF, Chrome, Safari if possible 编辑我需要支持IE9,FF,Chrome,Safari
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test</title>
<style>
div {
padding: 0px;
margin: 0px;
}
#fix {
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
background-color: red;
}
#my-wrap {
position: relative;
margin: 1em auto;
background-color: green;
width: 100%;
height: 100%;
}
#my-details {
position: absolute;
width: 50%;
max-width: 450px;
top: 20px;
background-color: yellow;
bottom: 0px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="fix">
<div id="my-wrap">
<div id="my-details">
<p>Lots of content in here....</p>
<br style="clear: both" />
</div>
</div>
</div>
</body>
</html>
Thanks! 谢谢!
The easiest approach would be to relatively position the #my-details
element as opposed to absolutely positioning it. 最简单的方法是相对
#my-details
元素进行相对定位,而不是绝对定位。 You could then simply use margin:0 auto
to center the element. 然后,您可以简单地使用
margin:0 auto
将元素居中。 Since the element is no longer absolutely positioned, you need to give it a height of 100%
. 由于元素不再绝对定位,因此需要将其高度设置为
100%
。 To displace top:20px
, you could simply use calc()
like so: height: calc(100% - 20px)
. 要替换
top:20px
,您可以像这样简单地使用calc()
: height: calc(100% - 20px)
。
#my-details {
position:relative;
margin:0 auto;
height:calc(100% - 20px);
width: 50%;
max-width: 450px;
top: 20px;
background-color: yellow;
bottom: 0px;
overflow: scroll;
}
As an alternative, you could change top:20px
to a percentage based value such as 2%
. 或者,您可以将
top:20px
更改为基于百分比的值,例如2%
。 You could then simply use a height of 98%
and avoid having to use calc()
. 然后,您可以简单地使用
98%
的高度,而不必使用calc()
。 Since that may not be an optimal solution, you could also use the following: 由于这可能不是最佳解决方案,因此您还可以使用以下方法:
#fix {
padding-top:1em;
}
#my-wrap {
padding-top:20px;
}
Basically, this method avoids top:20px
by adding a padding-top
value on the parent element instead. 基本上,此方法通过在父元素上添加
padding-top
值来避免top:20px
。 The parent of that element then receives a padding-top
value of 1em
to displace the margin: 1em auto
. 然后, 该元素的父级将收到
1em
的padding-top
值以替换margin: 1em auto
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.