【发布时间】:2021-11-30 11:37:59
【问题描述】:
我有一个包含一堆不同部分的 div,其中一个是 div 内的可滚动列表。
可滚动区域因屏幕大小而异,需要占据父级的所有剩余空间。到目前为止,我只知道如何在指定可滚动 div 的高度时使其滚动。当然,在处理不同的屏幕尺寸时,这不会有一个适合所有人的尺寸。
如果我将可滚动 div 的高度设置为 100%,那么我当然会失去滚动能力。所以这也不好。
我该如何解决这个问题?
这是一个说明问题的示例应用:
const App = () => {
return (
<div className="container">
<div>
<h2>My Content</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<h3>Scrollable section that must fill in the rest of the space</h3>
<div className="scrollable-div">
{[...Array(50).keys()].map((_, index) => (
<div>item {index}</div>
))}
</div>
</div>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
.container {
height: 500px;
border: 2px solid black;
overflow: hidden;
}
.scrollable-div {
overflow: auto;
border: 3px solid red;
/*
this all works fine, but I need the scroll section to go all the way to the end of the parent div,
regardless of the screen size. How can I do this without setting a fixed height here?
*/
height: 250px;
/*
the alternative, which would allow this div to expand all the way down to the reminder of the parent
is set height to 100%, however then I lose my ability to scroll.
*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
【问题讨论】:
-
在你的情况下,添加 height: 100vh;到 .scrollable-div ,它将占据窗口的其余部分,无论其大小。
-
@bigless 恐怕不是。如果不是因为需要滚动,这不会是问题。
-
@GLAPPsMobile 是的,它会的,但是列表中的一堆项目现在无法访问,因为滚动没有一直向下。
标签: javascript html css reactjs