100%高度的div,由于margin-top为50px,滚动条偏移了50px。溢出自动。

8
我正在尝试布局一个页面,顶部有一个水平导航栏和一个内容区域,在内容过大时将出现滚动条。

我目前的做法是使用一个div宽度为100%;高度为50px;绝对位置;顶部0;左侧0;然后是第二个div,高度为100%;宽度为100%; margin-top 50px; overflow:auto; 然而,出现的滚动条被50px的边距所抵消,因此将内容推到页面底部。如果我删除margin,它会正常工作,但它会将内容放在导航栏后面。

我还尝试将其包装在容器中,并尝试在子元素中设置margin和overflow,但这仍然没有达到所需的效果。

以下是jsFiddle链接,其中包含注释以更好地解释问题:

http://jsfiddle.net/Piercy/hggXJ/

HTML

<div id="nav">
  <h1>Navigation</h1>
</div>
<!-- <div id="contentContainer"> -->
  <div id="content">
    <div id="oversizeContent">
        <p>You can see the black border on this green box, but you cannot see the bottom black border. Similarly you cannot see the bottom arrow of the scrollbar.</p>
        <p>I tried putting a wrapper around the content and putting the margin on that but the scrollbar still over flows  Uncomment the contentContainer div and comment/uncomment the corresponding  css.</p>
    </div>
  </div>
<!-- <div> -->

CSS

html, body
{
  height:100%;
  overflow:hidden;
  color:white;
  font-weight:bold;
}

#nav
{
  height:50px;
  width:100%;
  background-color:red;
  position:absolute;
  top:0;
  left:0;
  z-index: 2;
}
#contentContainer
{
  /* uncomment this if you bring #contentContainer into play */
  /* 
      margin-top:50px;
      position:absolute;
      top:0;
      left:0;   
  */


  height:100%;
  width:100%; 

}
#content
{
  /* moving this into #contentContainer doesnt help either */
  /* comment this if you bring #contentContainer into play */

      margin-top:50px;
      position:absolute;
      top:0;
      left:0;



  width:100%;
  height:100%;

  background-color:blue;
  z-index: 1;
  overflow: auto;
}
#oversizeContent 
{
  background-color:green;
  width:400px;
  height:1000px;
  border:10px solid black;
}

你尝试过使用 #oversizeContent { margin-bottom: 50px; } 来解决这个问题吗? - gaynorvader
1个回答

11

height:100%; 改为 bottom:0;,它将会移动到相对父元素的底部,如果没有设置容器的 position:relative; 属性,则会移动到视口的底部。

演示


1
我必须保留margin-top,但添加bottom:0;并删除height:100%似乎可以解决问题!谢谢,http://jsfiddle.net/Piercy/E69TZ/1/ - Piercy
1
很高兴能帮忙!^_^ 如果您有绝对定位的元素,使用top、bottom、left和right属性而不是height和width属性通常非常方便。 - Martin Turjak
1
我还必须使用“position: fixed”而不是absolute,这样如果主页面有滚动条,100%高度的内容就不会被滚动出窗口。 - Soichi Hayashi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接