在CSS中,scrolling和heights(当元素嵌套深度超过1级时)似乎应该是一个初学者任务,我正在努力解决这个问题.
我想设计一些布局,其中默认元素不会扩展到父元素之后,如果扩展到父元素之后,就会有overflow: auto
个元素进入并开始滚动.
不过,我不想在每个元素上都设置height; 100%
,因为我需要元素只占用所需的空间,所以一直try 在每个元素上使用max-height: 100%
或max-height: inherit
.
使用height: 100%
时,即使元素嵌套在几层深的地方,也会正确拾取父元素的高度,如图所示:Code Pen 1
html {
padding: 0;
margin: 0;
overflow: hidden;
}
body {
height: 95vh;
background-color: red;
overflow: hidden;
}
.levelOne {
background-color: blue;
height: 100%;
/* Correctly gets parent height */
}
.levelTwo {
background-color: green;
overflow: auto;
height: 100%;
/* Correctly gets grand-parent height */
}
<div class="levelOne">
<div class=levelTwo>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
</div>
</div>
但是,当try 不使嵌套的div溢出max-height: 100%
时,级别1的子级似乎正确地停止在父级高度,但级别2的子级将溢出.Code Pen 2
*,
*:before,
*:after {
box-sizing: inherit;
max-height: inherit;
overflow: hidden;
}
html {
padding: 0;
margin: 0;
overflow: hidden;
}
body {
height: 95vh;
background-color: red;
overflow: hidden;
}
.levelOne {
background-color: blue;
max-height: 100%;
/* Correctly gets parent height*/
}
.levelTwo {
background-color: green;
overflow: auto;
max-height: 100%;
/* DOESN'T get grandparent hight, but spills out of levelOne so overflow: auto never starts to scroll; */
}
<div class="levelOne">
<div class=levelTwo>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
<p>Lorem</p>
</div>
</div>
- 为什么
max-height: 100%
不能达到祖父母的身高,而"身高:max-height: 100%
%"却达到了祖父母的身高?我本以为会有类似的行为. - 有没有更好的方法不允许元素溢出其父级大小?
我也看到过这样的建议,如果max-hight
不能计算出第一层的深度,它也会失败:
*, *:before, *:after {
box-sizing: inherit;
max-height: inherit;
overflow: hidden;
}
似乎出于某种原因,如果div是1x1 css网格,那么在更深层次上的工作会更加一致,但有时网格的开销太大,我希望能更好地理解其基本原理.
非常感谢.