CSS绝对子div溢出相对父级,切换相对元素

时间:2016-01-03 05:57:09

标签: html css

在以下示例中,绝对子div包含在相对父级中。显示父项之前的div并有条件地隐藏,因此无论是否显示标题,父div都应与顶部对齐。

问题是当显示标题时,即使滚动也无法隐藏子div的内容(无法看到滚动条的底部)。子div的底部怎么能是父div的底部(在这种情况下是浏览器窗口)?

html {
  height: 100%;
  margin: 0;
  overflow: hidden;
}
body {
  margin: 0;
  height: 100%;
}
#parentDiv 
{ 
  position:relative;
  background: yellow;
  height: 100%;
}
#childDiv 
{ 
  position:absolute; 
  left:50px; 
  top:20px;
  bottom: 0;
  background: blue;
  overflow: auto;
}
<div id='header'>This header causes childDiv to scroll outside of the browser window (bottom scroll thumb isn't visible).
  This toggles so parentDiv should adjust up when not visible.  
</div>
<div>
  <div id='parentDiv'>
    This is the parent div
    <div id='childDiv'>
      This is the child div <br>
      This is the child div <br>
      (Repeat to extend beyond browser window and cause a scroll bar to be displayed)
      ...
      This is the child div <br> 
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您的parentDiv包含在未指定高度的未命名div中。因此,将高度设置为100%不会执行任何操作,而parentDiv只会扩展到其内容。如果您只删除额外的div,则会显示滚动条。

但是,因为parentDiv的高度为100%,所以无论标题的高度如何,底部都将超出页面。要防止这种情况发生,您可以指定标题高度,并将parentDiv设置为在该高度之后开始。这是一个例子:

<html>
<head>
<style type="text/css">
html {
    height: 100%;
    margin: 0;
    overflow: hidden;
}
body {
    margin: 0;
    height: 100%;
}
#header {
    height: 10%;
}
#parentDiv 
{ 
    position:absolute;
    width: 100%;
    background: yellow;
    top: 10%;
    bottom: 0;
}
#childDiv 
{ 
    position:absolute; 
    left:50px; 
    top:20px;
    bottom: 0;
    background: blue;
    overflow: auto;
}
</style>
</head>
<body>
<div id='header'>This header causes childDiv to scroll outside of the browser window (bottom scroll thumb isn't visible).
This toggles so parentDiv should adjust up when not visible.  
</div>
<div id='parentDiv'>
    This is the parent div
    <div id='childDiv'>
        This is the child div <br>
        This is the child div <br>
        (Repeat to extend beyond browser window and cause a scroll bar to be displayed)
        ...
        This is the child div <br> 
    </div>
</div>
</body>
</html>