html - 如何强制嵌套 div 完全适合父级?

标签 html css

我正在尝试构建一个网页布局,其中有几个段落,后面有一个列表。

我希望页面的高度与视口(viewport)相同,如果 .lower 太高而无法在屏幕上显示,则 .lower 可以滚动。

body {
    overflow: hidden;
}

.lower {
    max-height: 100vh;
    overflow-y: scroll;
}

但是,使用此 CSS,我的 .lower 太高,最后几项不可见。我想我希望 .lower 的高度为(伪代码)100vh - height(.upper)

我可以使用 CSS 实现此布局吗?

body {
  overflow: hidden;
}
.lower {
  max-height: 100vh;
  border: 1px dotted red;
  overflow-y: scroll;
}
<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  <div class="upper">
    <p>hello world
    </p>
    <p>hello world again
    </p>
  </div>

  <div class="lower">
    <ul>
      <li>hello world 1</li>
      <li>hello world 2</li>
      <li>hello world 3</li>
      <li>hello world 4</li>
      <li>hello world 5</li>
      <li>hello world 6</li>
      <li>hello world 7</li>
      <li>hello world 8</li>
      <li>hello world 9</li>
      <li>hello world 10</li>
      <li>hello world 11</li>
      <li>hello world 12</li>
      <li>hello world 13</li>
      <li>hello world 14</li>
      <li>hello world 15</li>
      <li>hello world 16</li>
      <li>hello world 17</li>
      <li>hello world 18</li>
      <li>hello world 19</li>
      <li>hello world 20</li>
      <li>hello world 21</li>
      <li>hello world 22</li>
      <li>hello world 23</li>
      <li>hello world 24</li>
      <li>hello world 25</li>
      <li>hello world 26</li>
      <li>hello world 27</li>
      <li>hello world 28</li>
      <li>hello world 29</li>
      <li>hello world 30</li>
    </ul>
  </div>
</body>

</html>

最佳答案

如果可以接受上部元素使用固定(已知)高度,那么您可以使用 calc() :

Demo

body {
  height: 100vh;
  margin: 0;
  overflow: hidden;
}

.upper p {
  line-height: 20px;
  margin: 20px 0;
}

.lower {
  height: calc(100% - 100px);
  border: 1px dotted red;
  overflow-y: scroll;
  box-sizing: border-box;
}

我避免直接​​使用 vh 来表示 .lower,因为在 CSS calc() 中使用时会出现问题。

关于html - 如何强制嵌套 div 完全适合父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32870603/

相关文章:

php - 使用 MySQL 数据库中的数据在 HTML 中创建表不起作用

html - 在顶部同级具有固定位置的情况下向同级 div 添加 margin-top

javascript - 如何转换数据:image/svg+xml;base64 data from natural image?

javascript - 能否在 DOM 元素的样式对象更改后触发 JavaScript 钩子(Hook)?

php - 选择所有元素直到 - XPath

javascript - 为什么这个素数检查器有效?

html - Bootstrap Multicolumn Form-horizo​​ntal Styling only one one col-

css - 悬停后通过 Spry 菜单栏显示的图像

html - Twitter Bootstrap 在 Safari 5.1.7 中无法正常工作

html - 无法用边框水平放置我的所有图片,其中一张不断被压低