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

Ben*_*ird 135 html css scrollbar

我有这个div:

<div style='overflow:scroll; width:400px;height:400px;'>here is some text</div>
Run Code Online (Sandbox Code Playgroud)

即使文本没有溢出,滚动条也始终可见.我想让滚动条仅在必要时可见 - 也就是说,只有当盒子中有足够的文本需要它们时才可见.像textarea一样.我该怎么做呢?或者是我唯一的选择样式textarea所以它看起来像一个div?

Hid*_*dde 275

使用overflow: auto.滚动条仅在需要时显示.

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

  • 请注意,overflow-y仅在指定`max-height`时才起作用 (4认同)
  • Overflow-y 不需要 max-height。我从来没有将 max-height 与 Overflow-y 一起使用,而且每次都有效。 (3认同)
  • @Sumafu,你可能需要它,具体取决于具体情况,正如我现在所经历的那样。 (2认同)
  • 如果您在溢出元素上使用“绝对”或“固定”位置,则需要设置“高度”或“最大高度”,因为它们会阻止元素根据页面或视口边界调整大小。 (2认同)

kle*_*had 13

试试这个:

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Run Code Online (Sandbox Code Playgroud)


小智 11

将CSS的overflow属性修改blockauto.

overflow: auto;
Run Code Online (Sandbox Code Playgroud)

仅在需要时它才会自动向左侧添加滚动条。


pba*_*ris 6

尝试

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Run Code Online (Sandbox Code Playgroud)


Grv*_*agi 6

尝试

<div id="boxscroll2" style="overflow: auto; position: relative;" tabindex="5001">
Run Code Online (Sandbox Code Playgroud)