如何设置html元素,使其耗尽剩余的可视垂直空间
Posted
技术标签:
【中文标题】如何设置html元素,使其耗尽剩余的可视垂直空间【英文标题】:how to set html element such that it uses up remaining viewable vertical space 【发布时间】:2019-07-26 13:11:56 【问题描述】:我正在努力让溢出-y 部分按照代码中的描述运行。我有一个元素,它只占用与其内容一样多的垂直空间,并且在溢出时有父滚动。完整的代码可以在这里看到:https://jsfiddle.net/bmts8L5x/3/。为了满足 linter 的代码与非代码比率,我只需要在此处包含一部分代码。
header
background: yellow;
#first
overflow: hidden;
container
display: flex;
height: 100vh;
overflow: hidden;
#side
display: flex;
flex-direction: column;
width: 200px;
overflow: scroll;
#side>div
height: 200px;
html,
body
margin: 0;
padding: 0;
main>div:first-child
background: white;
height: 50px;
#big
background: pink;
border: solid;
overflow: scroll;
display: flex;
flex: 1;
#big>div
width: 1000px;
height: 100px;
/* I'd like to see #big take up the remaining space regardless of whether height here is 100px or 10000px */
<container>
<div id="side">
<div>
side nav does not scroll
</div>
<div>
item
</div>
<div>
item
</div>
<div>
item
</div>
<div>
item
</div>
<div>
item
</div>
</div>
<div id="first">
<header>
foo
</header>
<main>
<div>
this should remain visible after scrolling without needing position fixed
</div>
<header>
some other stuff
</header>
<div id="big">
<div>
this should take up the rest of the remaining viewable space and have any overflow be scrolled through.
<br /> X scrolls as expected but Y's overflow isn't contained to rest of viewable space.
</div>
</div>
</main>
</div>
</container>
【问题讨论】:
【参考方案1】:您可以更多地嵌套您的 flexbox - 将您的 #first
和 main
设为 列 flexbox
并将 height: 100%
分配给它:
#first, main
display: flex;
flex-direction: column;
height: 100%;
请看下面的演示:
header
background: yellow;
#first
overflow: hidden;
container
display: flex;
height: 100vh;
overflow: hidden;
#side
display: flex;
flex-direction: column;
width: 200px;
overflow: scroll;
#side>div
height: 200px;
html,
body
margin: 0;
padding: 0;
main>div:first-child
background: white;
height: 50px;
#big
background: pink;
border: solid;
overflow: scroll;
display: flex;
flex: 1;
#big>div
width: 1000px;
height: 100px;
/* ADDED */
#first, main
display: flex;
flex-direction: column;
height: 100%;
<container>
<div id="side">
<div>side nav does not scroll</div>
<div>item</div>
<div>item</div>
<div>item</div>
<div>item</div>
<div>item</div>
</div>
<div id="first">
<header>foo</header>
<main>
<div>
this should remain visible after scrolling without needing position fixed
</div>
<header>
some other stuff
</header>
<div id="big">
<div>
this should take up the rest of the remaining viewable space and have any overflow be scrolled through.
<br /> X scrolls as expected but Y's overflow isn't contained to rest of viewable space.
</div>
</div>
</main>
</div>
</container>
【讨论】:
这是否意味着如果我想要我想要的行为,我必须将所有祖先元素设置为 flexbox? 这不是一个要求...事实上 flexbox 属性只影响直接子元素,但在这里 stretch 到高度,在这里定义一个嵌套的 flexbox 似乎很有用...以上是关于如何设置html元素,使其耗尽剩余的可视垂直空间的主要内容,如果未能解决你的问题,请参考以下文章
css 这定义了在分配剩余空间之前元素的默认大小。主尺寸值使其与宽度或高度匹配