我们需要为div的溢出文本设置垂直滚动条.问题是,当我们将高度设置为100%并溢出为auto时,由于它前面有另一个同级div,它会扩展到其父容器之外.这是一个示例:
We need to instate a vertical scrollbar for overflow text of a div. The problem is when we set the height to 100% and overflow to auto, it expands beyond its parent container because of another sibling div preceding it. Here is an example:
<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 使用高度,但这会导致高度溢出而不显示滚动条.
app-body set to 100% causes it to have a height of 100px which makes it overflow beyond the bottom of container by 2em. We tried not using a height at all for app-body but that causes it to overflow without the scrollbar displayed.
我知道我们可以将高度设置为较小的百分比或固定的像素数,但是如果字体大小更改,这会对我们造成问题.如果 100%-2em 的高度有效,那将是我们试图定义的有效高度.
I know we could set the height to a smaller percentage or a fixed number of pixels but that will cause problems for us if the font size changes. If a height of 100% - 2em was valid then that would be effectively what we are trying to define.
推荐答案尝试一下,将app-body位置设置为绝对,然后将顶部固定为3em,其余固定为0:
Try this, setting the app-body positioning to absolute and then fixed the top to 3em and the rest to 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浏览器的测试.
PS: Above tested on FF3.6, IE8, Webkit browsers.
更多推荐
子div的高度溢出父容器
发布评论