我们需要为div的溢出文本设置垂直滚动条.问题是当我们将高度设置为100%并溢出到auto时,它会扩展到其父容器之外,因为它前面有另一个兄弟div.这是一个例子:
<style type="text/css">
.container {height: 100px; width: 100px; border: solid;}
.titlebar {height: 2em; background: gray;}
.app-body {height: 100%; overflow: auto; background: lightblue;}
</style>
...
<div class="container">
<div class="titlebar"></div>
<div class="app-body">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec condimentum pretium nisl.</div>
</div>Run Code Online (Sandbox Code Playgroud)
app-body设定为100%,则它以具有100像素的高度,这使得它溢出超出的底部container通过2em.我们尝试根本不使用高度app-body但是导致它溢出而没有显示滚动条.
我知道我们可以将高度设置为较小的百分比或固定数量的像素,但如果字体大小改变,这将导致我们的问题.如果高度100% - 2em有效,那么这将是我们试图定义的.
试试这个,将app-body定位设置为绝对值,然后将顶部固定为3em,其余部分固定为0:
<style type="text/css">
.container {height: 100px; width: 100px; border: solid;
position: relative;}
.titlebar {height: 2em; background: gray;
position: relative;}
.app-body {height: auto; overflow: auto; background: lightblue;
position: absolute; top: 2em; left: 0; right: 0; bottom: 0;}
</style>
Run Code Online (Sandbox Code Playgroud)
PS:以上在FF3.6,IE8,Webkit浏览器上测试过.