Jsfiddle显示问题:https://jsfiddle.net/ibrewster/g6v2x7ku/12/
注意粉红色div如何扩展到蓝色div的边界之外.
我正在尝试制作一个简单的布局,其中我有两个嵌套的div扩展到一定的高度(在这种情况下需要100%的窗口高度),内部div根据需要滚动以显示其他内容.因此,如果内容很短,则div全部折叠到内容的大小,但如果它很长,它们只会扩展到一个点,此时内部div应该滚动.
HTML:
<div id="topDiv">
<div id="insideDiv">
Some inside content
<br> More inside content
<br> More inside content
<br> More inside content
<br> More inside content
<br>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
而CSS:
html,
body {
height: 100%;
}
#topDiv {
background-color: lightblue;
max-height: 50px;
width: 100%;
padding: 10px;
}
#insideDiv {
background-color: pink;
max-height: 100%;
overflow-y:auto;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果将max-height topDiv设置为百分比,则效果相同,在这种情况下,我不能简单地将max-height值设置insideDiv为适当的较小值.此外,将overflow属性设置topDiv为隐藏不起作用 - 额外的内容insideDiv只是完全隐藏,然后滚动无法访问.
如何限制的高度insideDiv不超过高度topDiv,以insideDiv根据需要滚动任何额外的内容?
小智 30
您可以将自己#insideDiv的max-heightCSS属性更改100%为inherit.所以这个规则是这样的:
max-height: inherit;
box-sizing:border-box;如果你走这条路线,你也可能想要添加,因为这将允许任何边框或填充#insideDiv表现为(可能)所需.
这个问题的原因是max-height:100%;寻找父母的height,而不是它max-height的高度.因此,您最终得到了经典的非确定性相对高度问题.如果您给父母一个确定性height(而不是max-height),100%可以确定性地解决.
尝试这种flexbox布局,无论固定高度还是百分比高度/最大高度,它都能正常工作。
html, body {
height: 100%;
margin: 0;
}
#topDiv {
background-color: lightblue;
max-height: 50%;
padding: 10px;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
#insideDiv {
background-color: pink;
overflow-y: auto;
}Run Code Online (Sandbox Code Playgroud)
<div id="topDiv">
<div>
No scroll content
</div>
<div id="insideDiv">
Some inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>More inside content
<br>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43055 次 |
| 最近记录: |