子div的高度溢出父容器

编程入门 行业动态 更新时间:2024-10-27 20:25:32
本文介绍了子div的高度溢出父容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们需要为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的高度溢出父容器

本文发布于:2023-10-08 04:36:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   高度   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!