CSS 在 HTML 页面上隐藏滚动条

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3296644/
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 22:25:32  来源:igfitidea点击:

Hiding the scroll bar on an HTML page

cssbrowserscrollbar

提问by ANP

Can CSS be used to hide the scroll bar? How would you do this?

CSS可以用来隐藏滚动条吗?你会怎么做?

采纳答案by jao

Set overflow: hidden;on the body tag like this:

overflow: hidden;像这样在 body 标签上设置:

<style type="text/css">
    body {
        overflow: hidden;
    }
</style>

The code above hides both the horizontal and vertical scrollbar.

上面的代码隐藏了水平和垂直滚动条。

If you want to hide only the vertical scrollbar, use overflow-y:

如果只想隐藏垂直滚动条,请使用overflow-y

<style type="text/css">
    body {
        overflow-y: hidden;
    }
</style>

And if you want to hide only the horizontal scrollbar, use overflow-x:

如果您只想隐藏水平滚动条,请使用overflow-x

<style type="text/css">
    body {
        overflow-x: hidden;
    }
</style>


Note: It'll also disable the scrolling feature. Refer to the below answers if you just want to hide the scroll bar, but not the scroll feature.

注意:它还会禁用滚动功能。如果您只想隐藏滚动条而不是滚动功能,请参阅以下答案。

回答by Peter

WebKit supports scrollbar pseudo elements that can be hidden with standard CSS rules:

WebKit 支持可以使用标准 CSS 规则隐藏的滚动条伪元素:

#element::-webkit-scrollbar {
    display: none;
}

If you want all scrollbars hidden, use

如果您想隐藏所有滚动条,请使用

::-webkit-scrollbar {
    display: none;
}

I'm not sure about restoring - this did work, but there might be a right way to do it:

我不确定恢复 - 这确实有效,但可能有正确的方法来做到这一点:

::-webkit-scrollbar {
    display: block;
}

You can of course always use width: 0, which can then be easily restored with width: auto, but I'm not a fan of abusing widthfor visibility tweaks.

您当然可以始终使用width: 0,然后可以使用 轻松恢复width: auto,但我不喜欢滥用width可见性调整。

Firefox 64 now supports the experimental scrollbar-width propertyby default (63 requires a configuration flag to be set). To hide the scrollbar in Firefox 64:

Firefox 64 现在默认支持实验性scrollbar-width 属性(63 需要设置配置标志)。在 Firefox 64 中隐藏滚动条:

#element {
    scrollbar-width: none;
}

To see if your current browser supports either the pseudo element or scrollbar-width, try this snippet:

要查看您当前的浏览器是否支持伪元素或scrollbar-width,请尝试以下代码段:

.content {
  /* These rules create an artificially confined space, so we get
     a scrollbar that we can hide. They are not directly involved in
     hiding the scrollbar. */

  border: 1px dashed gray;
  padding: .5em;

  white-space: pre-wrap;
  height: 5em;
  overflow-y: scroll;
}

.content {
  /* This is the magic bit for Firefox */
  scrollbar-width: none;
}

.content::-webkit-scrollbar {
  /* This is the magic bit for WebKit */
  display: none;
}
<div class='content'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eu
urna et leo aliquet malesuada ut ac dolor. Fusce non arcu vel ligula
fermentum sodales a quis sapien. Sed imperdiet justo sit amet venenatis
egestas. Integer vitae tempor enim. In dapibus nisl sit amet purus congue
tincidunt. Morbi tincidunt ut eros in rutrum. Sed quam erat, faucibus
vel tempor et, elementum at tortor. Praesent ac libero at arcu eleifend
mollis ut eget sapien. Duis placerat suscipit eros, eu tempor tellus
facilisis a. Vivamus vulputate enim felis, a euismod diam elementum
non. Duis efficitur ac elit non placerat. Integer porta viverra nunc,
sed semper ipsum. Nam laoreet libero lacus.

Sed sit amet tincidunt felis. Sed imperdiet, nunc ut porta elementum,
eros mi egestas nibh, facilisis rutrum sapien dolor quis justo. Quisque
nec magna erat. Phasellus vehicula porttitor nulla et dictum. Sed
tincidunt scelerisque finibus. Maecenas consequat massa aliquam pretium
volutpat. Duis elementum magna vel velit elementum, ut scelerisque
odio faucibus.
</div>



(Note that this is not really a correct answer to the question, because it hides the horizontal bars as well, but that's what I was looking for when Google pointed me here, so I figured I'd post it anyway.)

(请注意,这并不是问题的正确答案,因为它也隐藏了单杠,但这正是 Google 将我指向此处时所寻找的内容,所以我想无论如何我都会发布它。)

回答by davidcondrey

Yes, sort of..

是的,有点..

When you ask the question, "Can the scroll-bars of a browser be removed in some way, rather than simply hidden or camouflaged", everyone will say "Not possible" because it is not possible to removethe scrollbars from all browsers in a compliant and cross-compatible way, and then there's the whole argument of usability.

当你问“浏览器的滚动条是否可以以某种方式删除,而不是简单地隐藏或伪装”这个问题时,每个人都会说“不可能”,因为不可能在一个浏览器中删除所有浏览器的滚动条。兼容和交叉兼容的方式,然后是可用性的整个论点。

However, it is possible to prevent the browser from ever having the need to generate and display scrollbars if you do not allow your webpage to overflow.

但是,如果您不允许网页溢出,则可以防止浏览器需要生成和显示滚动条。

This just means that we have to proactively substitute the same behavior that the browser would typically do for us and tell the browser thanks but no thanks buddy. Rather than try to remove scrollbars (which we all know is not possible) we can avoid scrolling (perfectly feasible) and scroll within the elements that we make and have more control over.

这只是意味着我们必须主动替换浏览器通常会为我们做的相同行为,并告诉浏览器感谢但不感谢伙计。与其尝试删除滚动条(我们都知道这是不可能的),我们可以避免滚动(完全可行)并在我们制作的元素内滚动并有更多控制权。

Create a div with overflow hidden. Detect when the user attempts to scroll, but is unable to because we've disabled the browsers ability to scroll with overflow: hidden.. and instead move the content up using JavaScript when this occurs. Thereby creating our own scrolling without the browsers default scrolling or use a plugin like iScroll.

创建一个隐藏溢出的 div。检测用户何时尝试滚动,但无法滚动,因为我们禁用了浏览器滚动溢出的能力:隐藏.. 并在发生这种情况时使用 JavaScript 将内容向上移动。从而在没有浏览器默认滚动的情况下创建我们自己的滚动或使用像iScroll这样的插件。

---

---

For the sake of being thorough; all the vendor specific ways of manipulating scroll-bars:

为了彻底;所有供应商特定的操作滚动条的方法:

Internet Explorer 5.5+

Internet Explorer 5.5+

*These properties were never part of the CSS specification, nor were they ever approved or vendor prefixed, but they work in Internet Explorer and Konqueror. These can also be set locally in the user style sheet for each application. In Internet Explorer you find it under the "Accessibility" tab, in Konqueror under the "Stylesheets" tab.

*这些属性从来不是 CSS 规范的一部分,也从来没有被批准或供应商前缀,但它们在 Internet Explorer 和 Konqueror 中有效。这些也可以在每个应用程序的用户样式表中本地设置。在 Internet Explorer 中,您可以在“辅助功能”选项卡下找到它,在 Konqueror 中的“样式表”选项卡下。

body, html { /* These are defaults and can be replaced by hexadecimal color values */
    scrollbar-base-color: aqua;
    scrollbar-face-color: ThreeDFace;
    scrollbar-highlight-color: ThreeDHighlight;
    scrollbar-3dlight-color: ThreeDLightShadow;
    scrollbar-shadow-color: ThreeDDarkShadow;
    scrollbar-darkshadow-color: ThreeDDarkShadow;
    scrollbar-track-color: Scrollbar;
    scrollbar-arrow-color: ButtonText;
}

As of Internet Explorer 8 these properties were vendor prefixed by Microsoft, but they were still never approved by W3C.

从 Internet Explorer 8 开始,这些属性由 Microsoft 加上供应商前缀,但它们仍未得到W3C 的批准。

-ms-scrollbar-base-color
-ms-scrollbar-face-color
-ms-scrollbar-highlight-color
-ms-scrollbar-3dlight-color
-ms-scrollbar-shadow-color
-ms-scrollbar-darkshadow-color
-ms-scrollbar-base-color
-ms-scrollbar-track-color

Further details about Internet Explorer

有关 Internet Explorer 的更多详细信息

Internet Explorer makes scrollavailable which sets whether or not to disable or enable scroll bars; it can also be used to get the value of the position of the scroll bars.

Internet Explorerscroll提供可设置是否禁用或启用滚动条;它还可用于获取滚动条位置的值。

With Microsoft Internet Explorer 6 and later, when you use the !DOCTYPEdeclaration to specify standards-compliant mode, this attribute applies to the HTML element. When standards-compliant mode is not specified, as with earlier versions of Internet Explorer, this attribute applies to the BODYelement, NOTthe HTMLelement.

对于 Microsoft Internet Explorer 6 及更高版本,当您使用!DOCTYPE声明指定符合标准的模式时,此属性适用于 HTML 元素。如果没有指定标准兼容模式,与早期版本的Internet Explorer,此属性适用于该BODY元素,不是HTML元素。

It's also worth noting that when working with .NET the ScrollBar class in System.Windows.Controls.Primitivesin the Presentation framework is responsible for rendering the scrollbars.

还值得注意的是,当使用 .NETSystem.Windows.Controls.Primitives时,Presentation 框架中的 ScrollBar 类负责呈现滚动条。

http://msdn.microsoft.com/en-us/library/ie/ms534393(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/ie/ms534393(v=vs.85).aspx



WebKit

网页套件

WebKit extensions related to scroll-bar customization are:

与滚动条自定义相关的 WebKit 扩展是:

::-webkit-scrollbar {}             /* 1 */
::-webkit-scrollbar-button {}      /* 2 */
::-webkit-scrollbar-track {}       /* 3 */
::-webkit-scrollbar-track-piece {} /* 4 */
::-webkit-scrollbar-thumb {}       /* 5 */
::-webkit-scrollbar-corner {}      /* 6 */
::-webkit-resizer {}               /* 7 */

Enter image description here

在此处输入图片说明

These can each be combined with additional pseudo-selectors:

这些都可以与额外的伪选择器结合使用:

  • :horizontal– The horizontal pseudo-class applies to any scrollbar pieces that have a horizontal orientation.
  • :vertical– The vertical pseudo-class applies to any scrollbar pieces that have a vertical orientation.
  • :decrement– The decrement pseudo-class applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view's position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).
  • :increment– The increment pseudo-class applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view's position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).
  • :start– The start pseudo-class applies to buttons and track pieces. It indicates whether the object is placed before the thumb.
  • :end– The end pseudo-class applies to buttons and track pieces. It indicates whether the object is placed after the thumb.
  • :double-button– The double-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.
  • :single-button– The single-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.
  • :no-button– Applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.
  • :corner-present– Applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.
  • :window-inactive– Applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)
  • :horizontal– 水平伪类适用于任何具有水平方向的滚动条。
  • :vertical– 垂直伪类适用于任何具有垂直方向的滚动条。
  • :decrement– 递减伪类适用于按钮和轨道件。它指示按钮或轨道在使用时是否会减少视图的位置(例如,在垂直滚动条上向上,在水平滚动条上向左)。
  • :increment– 增量伪类适用于按钮和轨道件。它指示按钮或轨道在使用时是否会增加视图的位置(例如,在垂直滚动条上向下,在水平滚动条上向右)。
  • :start– start 伪类适用于按钮和轨道件。它指示对象是否放置在拇指之前。
  • :end– end 伪类适用于按钮和轨道件。它指示对象是否放置在拇指之后。
  • :double-button– 双按钮伪类适用于按钮和轨道件。它用于检测按钮是否是位于滚动条同一端的一对按钮的一部分。对于轨道件,它指示轨道件是否紧靠一对按钮。
  • :single-button– 单按钮伪类适用于按钮和轨道件。它用于检测按钮是否单独位于滚动条的末尾。对于轨道件,它指示轨道件是否与单例按钮相邻。
  • :no-button– 适用于轨道块,指示轨道块是否运行到滚动条的边缘,即轨道的那端没有按钮。
  • :corner-present– 适用于所有滚动条片段并指示是否存在滚动条角。
  • :window-inactive– 适用于所有滚动条并指示包含滚动条的窗口当前是否处于活动状态。(在最近的夜生活中,这个伪类现在也适用于 ::selection。我们计划扩展它以处理任何内容,并将其作为新的标准伪类提出。)

Examples of these combinations

这些组合的例子

::-webkit-scrollbar-track-piece:start { /* Select the top half (or left half) or scrollbar track individually */ }
::-webkit-scrollbar-thumb:window-inactive { /* Select the thumb when the browser window isn't in focus */ }
::-webkit-scrollbar-button:horizontal:decrement:hover { /* Select the down or left scroll button when it's being hovered by the mouse */ }

Further details about Chrome

有关 Chrome 的更多详细信息

addWindowScrollHandlerpublic static HandlerRegistration addWindowScrollHandler(Window.ScrollHandler handler)

  Adds a Window.ScrollEvent handler Parameters:   handler - the handler Returns:   returns the handler registration [source](http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/Window.html#addWindowScrollHandler(com.google.gwt.user.client.Window.ScrollHandler))

addWindowScrollHandlerpublic static HandlerRegistration addWindowScrollHandler(Window.ScrollHandler handler)

  添加 Window.ScrollEvent 处理程序参数:处理程序 - 处理程序返回:返回处理程序注册 [来源]( http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/Window.html# addWindowScrollHandler(com.google.gwt.user.client.Window.ScrollHandler))



Mozilla

Mozilla

Mozilla does have some extensions for manipulating the scroll-bars, but they are all recommended not to be used.

Mozilla 确实有一些用于操作滚动条的扩展,但不建议使用它们。

  • -moz-scrollbars-noneThey recommend using overflow:hidden in place of this.
  • -moz-scrollbars-horizontalSimilar to overflow-x
  • -moz-scrollbars-verticalSimilar to overflow-y
  • -moz-hidden-unscrollableOnly works internally within a users profile settings. Disables scrolling XML root elements and disables using arrow keys and mouse wheel to scroll web pages.

  • Mozilla Developer Docs on 'Overflow'

  • -moz-scrollbars-none他们建议使用 overflow:hidden 来代替。
  • -moz-scrollbars-horizontal类似于溢出-x
  • -moz-scrollbars-vertical类似于溢出-y
  • -moz-hidden-unscrollable仅在用户配置文件设置内部工作。禁用滚动 XML 根元素并禁用使用箭头键和鼠标滚轮滚动网页。

  • 关于“溢出”的 Mozilla 开发人员文档

Further details about Mozilla

有关 Mozilla 的更多详细信息

This is not really useful as far as I know, but it's worth noting that the attribute which controls whether or not scrollbars are displayed in Firefox is (reference link):

据我所知,这并不是很有用,但值得注意的是,控制是否在 Firefox 中显示滚动条的属性是(参考链接):

  • Attribute:       scrollbars
  • Type:              nsIDOMBarProp
  • Description:  The object that controls whether or not scrollbars are shown in the window. This attribute is "replaceable" in JavaScript. Read only
  • 属性:       滚动条
  • 类型:              nsIDOMBarProp
  • 描述:  控制滚动条是否显示在窗口中的对象。这个属性在 JavaScript 中是“可替换的”。只读

Last but not least, padding is like magic.

最后但并非最不重要的一点是,填充就像魔术一样。

As has been previously mentioned in some other answers, here is an illustration which is sufficiently self-explanatory.

正如之前在其他一些答案中提到的那样,这里有一个说明,它是不言自明的。

Enter image description here

在此处输入图片说明



History lesson

历史课

Scroll bars

滚动条

Just because I'm curious, I wanted to learn about the origin of scrollbars, and these are the best references I found.

只是因为好奇,我想了解滚动条的起源,这些是我找到的最好的参考资料。

Miscellaneous

各种各样的

In an HTML5 specification draft, the seamlessattribute was defined to prevent scroll-bars from appearing in iFrames so that they could be blended with surrounding content on a page. Though this element does not appear in the latest revision.

在 HTML5 规范草案中,该seamless属性被定义为防止滚动条出现在 iFrame 中,以便它们可以与页面上的周围内容混合。虽然这个元素没有出现在最新版本中。

The scrollbarBarProp object is a child of the windowobject and represents the user interface element that contains a scrolling mechanism, or some similar interface concept. window.scrollbars.visiblewill return trueif the scroll bars are visible.

scrollbarBarProp 对象是该对象的子window对象,表示包含滚动机制或某些类似界面概念的用户界面元素。如果滚动条可见,window.scrollbars.visible将返回true

interface Window {
  // The current browsing context
  readonly attribute WindowProxy window;
  readonly attribute WindowProxy self;
           attribute DOMString name;
  [PutForwards=href] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute UndoManager undoManager;
  Selection getSelection();
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  void close();
  void focus();
  void blur();
  // Truncated

The History API also includes features for scroll restoration on page navigation to persist the scroll position on page load.

History API 还包括在页面导航中恢复滚动的功能,以在页面加载时保持滚动位置。

window.history.scrollRestorationcan be used to check the status of scrollrestoration or change its status (appending ="auto"/"manual". Auto is the default value. Changing it to manual means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app's history. If you need to, you can keep track of the scroll position as you push history entries with history.pushState().

window.history.scrollRestoration可用于检查滚动恢复的状态或更改其状态(附加="auto"/"manual". Auto 是默认值。将其更改为手动意味着您作为开发人员将拥有用户遍历应用程序历史记录时可能需要的任何滚动更改的所有权. 如果需要,您可以在使用 history.pushState() 推送历史条目时跟踪滚动位置。

---

---

Further reading:

进一步阅读:

Examples

例子

回答by thgaskell

You can accomplish this with a wrapper divthat has its overflow hidden, and the inner divset to auto.

您可以使用div隐藏其溢出且内部div设置为auto.

To remove the inner div's scroll bar, you can pull it out of the outer div's viewport by applying a negative margin to the inner div. Then apply equal padding to the inner div so that the content stays in view.

要移除内部div的滚动条,您可以div通过对内部应用负边距将其从外部的视口中拉出div。然后对内部 div 应用相等的填充,以便内容保持在视图中。

JSFiddle

JSFiddle

HTML

HTML

<div class="hide-scroll">
    <div class="viewport">
        ...
    </div>
</div>

CSS

CSS

.hide-scroll {
    overflow: hidden;
}

.viewport {
    overflow: auto;

    /* Make sure the inner div is not larger than the container
     * so that we have room to scroll.
     */
    max-height: 100%;

    /* Pick an arbitrary margin/padding that should be bigger
     * than the max width of all the scroll bars across
     * the devices you are targeting.
     * padding = -margin
     */
    margin-right: -100px;
    padding-right: 100px;
}

回答by Hristo Eftimov

This works for me with simple CSS properties:

这对我来说适用于简单的 CSS 属性:

.container {
    -ms-overflow-style: none;  // Internet Explorer 10+
    scrollbar-width: none;  // Firefox
}
.container::-webkit-scrollbar { 
    display: none;  // Safari and Chrome
}

For older versions of Firefox, use: overflow: -moz-scrollbars-none;

对于旧版本的 Firefox,请使用: overflow: -moz-scrollbars-none;

回答by Wilf

Here's my solution, which theoretically covers all modern browsers:

这是我的解决方案,理论上涵盖了所有现代浏览器:

html {
    scrollbar-width: none; /* For Firefox */
    -ms-overflow-style: none; /* For Internet Explorer and Edge */
}

html::-webkit-scrollbar {
    width: 0px; /* For Chrome, Safari, and Opera */
}

htmlcan be replaced with any element you want to hide the scrollbar of.

html可以替换为您想要隐藏滚动条的任何元素。

Note: I've skimmed the other 19 answers to see if the code I'm posting has already been covered, and it seems like no single answer sums up the situation as it stands in 2019, although plenty of them go into excellent detail. Apologies if this has been said by someone else and I missed it.

注意:我浏览了其他 19 个答案,看看我发布的代码是否已经被覆盖,似乎没有一个答案可以概括 2019 年的情况,尽管其中很多都非常详细。如果这已经被其他人说过而我错过了,我深表歉意。

回答by Ben Yo

I think I found a workaround for you guys if you're still interested. This is my first week, but it worked for me...

如果您仍然感兴趣,我想我为你们找到了解决方法。这是我的第一周,但它对我有用......

<div class="contentScroller">
    <div class="content">
    </div>
</div>

.contentScroller {overflow-y: auto; visibility: hidden;}
.content {visibility: visible;}

回答by Alex

If you're looking for a solution to hide a scrollbar for mobile devices, follow Peter's answer!

如果您正在寻找隐藏移动设备滚动条的解决方案,请按照Peter 的回答进行操作

Here's a jsfiddle, which uses the solution below to hide a horizontal scrollbar.

这是一个jsfiddle,它使用下面的解决方案来隐藏水平滚动条。

.scroll-wrapper{
    overflow-x: scroll;
}
.scroll-wrapper::-webkit-scrollbar { 
    display: none; 
}

It was tested on a Samsung tablet with Android 4.0.4 (Ice Cream Sandwich, both in the native browser and Chrome) and on an iPad with iOS 6 (both in Safari and Chrome).

它在装有 Android 4.0.4(Ice Cream Sandwich,本机浏览器和 Chrome)的三星平板电脑和装有 iOS 6 的 iPad(Safari 和 Chrome)上进行了测试。

回答by JoshW

In addition to Peter's answer:

除了彼得的回答:

#element::-webkit-scrollbar {
    display: none;
}

This will work the same for Internet Explorer 10:

这将适用于 Internet Explorer 10:

 #element {
      -ms-overflow-style: none;
 }

回答by Sergiy Sokolenko

Use the CSS overflowproperty:

使用CSSoverflow属性

.noscroll {
  width: 150px;
  height: 150px;
  overflow: auto; /* Or hidden, or visible */
}

Here are some more examples:

以下是更多示例: