如何设置div使用一定百分比的高度,同时使用overflow:auto放置滚动条?

发布于 2024-10-06 22:56:44 字数 229 浏览 4 评论 0原文

我有以下代码:

div.leftnav {
    overflow: auto ;
    height: 50% ;
}

当我设置此类的大 div 时,它不起作用(它不显示滚动条,也不将其大小调整为 50%,但是如果我使用

height: 400px ;

或其他一些“绝对”, 它就可以完美工作“ 价值。

I have the following code:

div.leftnav {
    overflow: auto ;
    height: 50% ;
}

That, when I set a big div of this class, does not work (it doesn't show the scrollbar nor resize it to 50%, however it works perfectly if instead if I use

height: 400px ;

Or some other "absolute" value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

临风闻羌笛 2024-10-13 22:56:44

仅当父元素也有高度指令时,高度才会起作用。

假设您有非常简单的标记:

<html>
    <body>
        <div class="leftnav">
            really long text
        </div>
    </body>
</html>

那么以下 CSS 将为您工作:

div.leftnav {
    overflow: auto ;
    height: 50%;
}
html, body { 
    height:100%;
}

不过,您始终需要有高度说明。如果父元素之一缺少高度指令,则 100% 对 div 没有任何意义。如果您无法访问树下的所有元素,那么您将需要一个具有固定高度的父元素:

<div class="leftnav-container">
    <div class="leftnav">
        really long text
    </div>
</div>

然后您需要这个 css :

div.leftnav {
    overflow: auto ;
    height: 50%;
}
div.leftnav-container {
    height : 500px;
}

height will only work if the parent element has a height instruction as well.

So say you have really simple markup :

<html>
    <body>
        <div class="leftnav">
            really long text
        </div>
    </body>
</html>

Then the following CSS will work for you :

div.leftnav {
    overflow: auto ;
    height: 50%;
}
html, body { 
    height:100%;
}

You need to have height instructions all the way though. If there is a height instruction missing on one of the parent elements, then the 100% won't mean anything to the div. If you can't access all the elements down the tree, then you will need a parent element with a fixed height :

<div class="leftnav-container">
    <div class="leftnav">
        really long text
    </div>
</div>

Then you need this css :

div.leftnav {
    overflow: auto ;
    height: 50%;
}
div.leftnav-container {
    height : 500px;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文