如何使用CSS来定位固定的可变高度标题和可滚动内容框? [英] How do I use CSS to position a fixed variable height header and a scrollable content box?
问题描述
我试图制作一个具有固定标题和可滚动内容区域的网页。当标题具有已知的高度时,这是微不足道的,但我正在努力找到一个解决方案,当标题是流动的。
I'm trying to make a web page with a fixed header and a scrollable content area. This is trivial when the header has a known height but I'm struggling to find a solution for when the header is fluid.
我想要的布局是:
--------------
head
--------------
content
--------------
其中head是其内容需要的高度,content没有最小高度,但会在可滚动之前达到视口底部的最大高度。
where "head" is whatever height it's content needs it to be and "content" has no minimum height but will reach a maximum height of the bottom of the viewport before becoming scrollable.
这些天可能在纯CSS吗?我的目标是IE8 +。
Is this possible these days in pure CSS? I'm targeting IE8+.
为了阐明我想要的,这里是我
To clarify what I want, here is what I would do if I knew the height of the header:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
margin: 0;
}
#head {
background: yellow;
height: 20px; /* I can't rely on knowing this. */
}
#content {
background: red;
position: absolute;
top: 20px; /* here also */
bottom: 0;
width: 100%;
overflow: auto;
}
</style>
</head>
<body>
<div id="head">some variable height content</div>
<div id="content">
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
scrollable content<br/>
</div>
</body>
</html>
推荐答案
假设fixed c> position:fixed ,我认为在纯CSS中不可能,因为 position:fixed
将元素从文档流中移除。
Assuming by "fixed" you mean position:fixed
, I don't think it's possible in pure CSS, as position:fixed
takes the element out of the document flow.
但是,它应该只需要一两行JavaScript来得到你想要的。这样的东西(未经测试,只是为了示例的目的,将需要语法调整实际工作):
However, it should just take a line or two of JavaScript to get what you want. Something like this (untested, only for example purposes, will need syntax tweaked to actually work):
var height = document.getElementById("head").offsetHeight;
document.getElementById("content").style.marginTop = height + 'px';
这样的东西应该能够显示固定的< div> ; c>并设置内容
< div>
的保证金。您还需要在固定的< div>
上显式设置背景颜色,否则滚动时内容将显示为固定的。
Something like that should get you the rendered height of the fixed <div>
and set the content <div>
's margin accordingly. You'll also need to explicitly set a background color on the fixed <div>
, otherwise the content will appear to bleed into the fixed one when scrolling.
这篇关于如何使用CSS来定位固定的可变高度标题和可滚动内容框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!