0

我的项目有以下要求:

  1. 页眉固定在页面顶部
  2. 内容区域具有白色背景和 100% 高度
  3. 内容小于屏幕高度时没有滚动条
  4. 必须支持 IE7+(IE 的 JS 修复是可以的)
  5. 当内容高于屏幕高度时,滚动它应该停留在白色内容区域内(而不是在标题下方)。

这是我的基本 HTML:

<div class="wrap">
    <div id="header">header</div>
</div>
<div class="wrap" id="content">content</div>​

CSS:

body{background:#C0DEED url('https://si0.twimg.com/images/themes/theme1/bg.png') repeat-x 0px -80px fixed;}
html,body{height:100%;}
.wrap{width:300px; margin:0 auto;}
#header{position:fixed; background:#aaa; top:10px; width:300px;}
#content{height:100%; background:white; margin-top:40px}

​ 示例:http: //jsfiddle.net/zw3WS/

第一个问题是如何让内容具有 100% 的高度,而不是放在标题下方,并且仍然没有不必要的滚动条?

其次,如果内容比屏幕高,我如何让它只在空白处滚动,并且不允许内容像现在一样在 to 栏下滚动?

4

1 回答 1

1

对于“仅在空白区域”滚动,您可以通过设置position: fixedwrapper 元素,然后将 header 和 content 元素绝对定位在其中:

body{
  background:#C0DEED url('https://si0.twimg.com/images/themes/theme1/bg.png') repeat-x 0px -80px fixed;
  overflow: hidden; /* no scrollbars for page body */
}

.wrap {  
  width: 300px;
  position: fixed;
  top: 10px;
  left: 50%; /* for horizontal centering */
  margin-left: -150px; /* for vertical centering */
  bottom: 0;
}

#header{
  position: absolute; 
  background:#aaa; 
  top: 0;
  left: 0;
  right: 0;
}

#content{
  background:white; 
  position: absolute;
  bottom: 0;
  top: 30px;
  left: 0;
  right: 0;
  overflow: auto; /* this makes the scrollbar appear inside #content */
}

演示:http: //jsbin.com/osipin/1/edit


为了在页面正文中滚动,您需要向标记添加两个元素:标题的背景和内容的背景。

标题背景的目的是在向下滚动时遮盖内容,否则它会出现在标题下方。您用来覆盖内容的只是与页面相同的背景。您必须正确调整此 bg 元素的大小,以便它填充视口的宽度,并且是内容区域上边距的高度。真正的标题可以在这个 bg 元素中使用设置的宽度和margin: 0 auto.

内容背景元素应该是内容之前的空元素,并且具有固定的位置。其目的是确保即使内容短于视口高度,白色区域也能延伸到页面底部。

您的新 CSS 如下所示:

body, .header-bg {
  background:#C0DEED url(https://si0.twimg.com/images/themes/theme1/bg.png) repeat-x 0 -80px fixed;
}

.wrap {
  width:300px;
  margin: 0 auto;
}

.header-bg {
  position: fixed;
  top: 0px;
  left: 0;
  right: 0;
  height: 40px;
}

#header {
  background:#aaa;
  width:300px;
  margin: 10px auto 0;
}

.content-bg {
 background: #FFF;
  position: fixed;
  width: 300px;
  top: 40px;
  bottom: 0;
  z-index: -1;
}

你的新标记是这样的:

<div class="wrap">

  <div class="header-bg">
    <div id="header">header</div>
  </div>

  <div class="content-bg"></div>

    <div id="content">
      CONTENT
    </div>

</div>

演示:http: //jsbin.com/osipin/4/edit

于 2012-10-26T19:42:10.583 回答