Html 如何使 div 上的滚动条仅在必要时可见?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14732448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:27:02  来源:igfitidea点击:

How do I make the scrollbar on a div only visible when necessary?

csshtmlscrollbar

提问by Benubird

I have this div:

我有这个 div:

<div style='overflow:scroll; width:400px;height:400px;'>here is some text</div>

The scrollbars are always visible, even though the text does not overflow. I want to make the scrollbars only be visible when necessary - that is, only visible when there is enough text in the box that they are needed. Like a textarea does. How do I do this? Or is my only option to style a textarea so it looks like a div?

即使文本没有溢出,滚动条也始终可见。我想让滚动条只在必要时可见 - 也就是说,只有当框中有足够的文本时才可见。就像 textarea 一样。我该怎么做呢?或者是我唯一的选择来设置文本区域的样式,使其看起来像一个 div?

回答by Hidde

Use overflow: auto. Scrollbars will only appear when needed.

使用overflow: auto. 滚动条只会在需要时出现。

(Sidenote, you can also specify for only the x, or y scrollbar: overflow-x: autoand overflow-y: auto).

(旁注,您也可以仅指定 x 或 y 滚动条:overflow-x: autooverflow-y: auto)。

回答by kleinohad

try this:

尝试这个:

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

回答by pbaris

try

尝试

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

回答by GrvTyagi

try

尝试

<div id="boxscroll2" style="overflow: auto; position: relative;" tabindex="5001">

回答by Shailendra Kumar

I found that there is height of div still showing, when it have text or not. So you can use this for best results.

我发现 div 的高度仍然显示,无论是否有文本。因此,您可以使用它来获得最佳效果。

<div style=" overflow:auto;max-height:300px; max-width:300px;"></div>

回答by Papun Sahoo

You can try with below one:

您可以尝试使用以下方法:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>