2012-03-13 38 views
30

我有2个主div,标题和一个div中包含的滚动列表。 我希望标题始终保持在页面的顶部,并在下面滚动列表。 滚动条应该附加到滚动div而不是整个页面,即滚动条不会出现在标题的右侧,只是滚动div。标题div保持在顶部,垂直滚动div下面滚动条只附加到该div

这就是我想要实现:

______________________ 
|_______header_______| 
|     |*| 
| Container Div |*| 
|     |*| 
|     |*| 
|     |*| 
|     |*| 
|     |*| 
---------------------- 

* = scrollbar 

布局应该是液体,如果窗口被垂直拉伸,只有div容器,它的滚动条应该得到更长的时间。

我不想定位标头position: fixed;,因为滚动条将位于它的右侧,而不是位于其下方。

+0

'position:static'? – Jon 2012-03-13 03:17:09

回答

39

HTML:

​<div class="header">This is the header</div> 
<div class="content">This is the content</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

CSS:

​.header 
{ 
    height:50px; 
} 
.content 
{ 
    position:absolute; 
    top: 50px; 
    left:0px; 
    right:0px; 
    bottom:0px; 
    overflow-y:scroll;   
}​ 
+7

小提琴:http://jsfiddle.net/n9P3X/1/ – valentinas 2012-03-13 03:28:49

+0

谢谢,就是这样,这样简单的解决方案,不知道为什么它逃脱了我,哈哈。 – Garywoo 2012-03-13 03:37:35

+2

如果有'.content'没有到达页面底部的机会,请使用'overflow-y:auto;'。在这种情况下,它将移除滚动条。 – Keith 2016-08-15 00:47:46

1

这里是一个demo。使用position:fixed; top:0; left:0;,所以标题始终保持在最前面。

​#header { 
    background:red; 
    height:50px; 
    width:100%; 
    position:fixed; 
    top:0; 
    left:0;  
}.scroller { 
    height:300px; 
    overflow:scroll;  
} 
+0

这不会在主div上设置流体布局高度(比如100%),谢谢。 – Garywoo 2012-03-13 03:41:09

0

你需要用js获得更好的高度,体格

<html><body> 
<div id="head" style="height:50px; width=100%; font-size:50px;">This is head</div> 
<div id="body" style="height:700px; font-size:100px; white-space:pre-wrap; overflow:scroll;"> 
This is body 
T 
h 
i 
s 

i 
s 

b 
o 
d 
y 
</div> 
</body></html> 
6

找到flex魔力。

Here是如何执行固定标题和可滚动内容的示例。代码:

<!DOCTYPE html> 
<html style="height: 100%"> 
    <head> 
    <meta charset=utf-8 /> 
    <title>Holy Grail</title> 
    <!-- Reset browser defaults --> 
    <link rel="stylesheet" href="reset.css"> 
    </head> 
    <body style="display: flex; height: 100%; flex-direction: column"> 
    <div>HEADER<br/>------------ 
    </div> 
    <div style="flex: 1; overflow: auto"> 
     CONTENT - START<br/> 
     <script> 
     for (var i=0 ; i<1000 ; ++i) { 
      document.write(" Very long content!"); 
     } 
     </script> 
     <br/>CONTENT - END 
    </div> 
    </body> 
</html> 

*柔性解决方案的优点是,内容是独立于布局的其他部分。例如,内容不需要知道标题的高度。

对于完整的Holy Grail实现(页眉,页脚,导航,侧面和内容),使用柔性显示,请转至here

+2

这是一个天才的解决方案!这比100vh更好 – Student22 2017-11-14 05:37:49