【问题标题】:CSS absolute child div overflows relative parent, toggled relative elementCSS绝对子div溢出相对父,切换相对元素
【发布时间】:2016-04-07 01:00:18
【问题描述】:

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

问题是在显示header的时候,即使滚动也隐藏了子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>

【问题讨论】:

  • 那是因为#parentDiv的高度是100%,但是他的父母没有高度,所以#parentDiv的高度只能由他的内容This is the parent div设置。例如,如果您将#parentDiv 的高度设置为350px,您将看到#childDiv 的内容。
  • 我说错了。内容没有隐藏——只是标题大小的内容被隐藏了。如何在不明确考虑标题高度的情况下显示(或滚动)所有子 div。标题的内容可能会有所不同,从而使高度动态化。它可以显示或隐藏。

标签: html css


【解决方案1】:

您的 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>

【讨论】:

  • 你能想出一种方法来避免将父 div 设置为在前一个元素的高度之后开始吗?此高度可能因内容而异。它也可以被隐藏(即使用 jquery 切换方法)。
  • 嗯,也许这会有所帮助? stackoverflow.com/questions/17590457/…
猜你喜欢
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多