我正在尝试构建一个网页布局,其中有几个段落,后面有一个列表。
我希望页面的高度与视口(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()
:
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/