我有一个具有这种样式的弹性容器:
section {
width: 100vw;
height: 100vh;
display: flex;
overflow-y: scroll;
justify-content: center;
align-items: center;
flex-direction: column;
}
此部分有一些子项(比如两个带有 #one 和 #two id 的 div)。当我将它们的高度设置为
height: 100%;
时,我希望它们使该部分滚动(因为 2*100% = 200%,对吗?)。但相反,它们只是溢出了该部分。我该如何实现这个目标?
更具体地说,在以下 HTML 中:
<body>
<div id="root">
<section>
<div id="one">Hi im div 1!</div>
<div id="two">Hi im div 2!</div>
</section>
<section>
<div id="three">Hi im div 3!</div>
</section>
</div>
</body>
以及以下正文的 css 和
div#root
:
body{
width: 100vw;
height: 100vh;
overflow-x: hidden;
overflow-y: scroll;
scroll-behavior: smooth;
}
#root{
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#one, #two{
height : 100%;
}
我希望第一部分可滚动,第二部分完全适合视口。很明显,
div#root
也可以滚动。
正如您的描述,我创建了示例场景并且它正在运行。或者我错过了什么?
body{
width: 100vw;
height: 100vh;
overflow-x: hidden;
overflow-y: scroll;
scroll-behavior: smooth;
}
#root{
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.sec1{
height: 200px;
width: 200px;
overflow-y: scroll;
}
#one{
height: 250px;
}
<div id="root">
<section class="sec1">
<div id="one">Hi im div 1!</div>
<div id="two">Hi im div 2!</div>
</section>
<section>
<div id="three">Hi im div 3!</div>
</section>
</div>
你必须让该部分变短,这样它的内容就没有足够的空间来容纳,然后溢出会自动设置滚动
所以
section {
width: 100vw;
height: 25vh; //<--
display: flex;
overflow-y: auto;/*<-- scroll forces all sections to have handler and this is not recommended in you example*/
justify-content: center;
align-items: center;
flex-direction: column;
}
body {
width: 100%; /* <-- just to show you the scrollbar */
height: 100vh;
/* overflow-x: hidden;<-- no need */
/* overflow-y: scroll;<-- no need */
scroll-behavior: smooth;
}
#root {
width: 90%; /* <-- just to show you the scrollbar */
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#one,
#two {
height: 100%;
}
<div id="root">
<section>
<div id="one">Hi im div 1!</div>
<div id="two">Hi im div 2!</div>
</section>
<section>
<div id="three">Hi im div 3!</div>
</section>
</div>
Saurot的回答非常有帮助,但我发现解决方案是为子div设置flex: 0 0 100%
。谢谢大家! :D