繁体   English   中英

子div的高度溢出父容器

[英]Height of child div overflows parent container

我们需要为 div 的溢出文本设置一个垂直滚动条。 问题是当我们将高度设置为 100% 并将溢出设置为自动时,它会扩展到其父容器之外,因为它前面有另一个同级 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% 会导致它的高度为 100px,这使得它溢出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>

PS:以上在FF3.6、IE8、Webkit浏览器上测试过。

您可以将.container的溢出值设置为hidden如下所示:

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

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM