2010-02-01 211 views
4

我们需要为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>

app-body设定为100%,则它以具有100像素的高度,这使得它溢出超出container2em底部。我们尽量不使用高度为app-body,但导致它在没有滚动条显示的情况下溢出。

我知道我们可以将高度设置为较小的百分比或固定数量的像素,但是如果字体大小发生变化,这会对我们造成问题。如果100% - 2em的高度有效,那么这将是我们试图定义的有效方法。

回答

5

尝试此,设定该应用体定位到绝对,然后固定顶部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> 

PS:上FF3.6,IE8,WebKit浏览器以上测试。

-2

您可以设置.container溢出:隐藏,像这样:

<style type="text/css"> 
.container {height: 100px; width: 100px; border: solid;overflow: hidden;} 
</style> 

希望这有助于