使用 css 溢出自动隐藏垂直滚动条

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

Auto hiding vertical scrollbars using css overflow

css

提问by Rupam Datta

I came across a problem using css overflow for autohiding the vertical scrollbar. I read in a few articles to use css hover pseudo class to achieve this behaviour and the good thing is I am successful to some extent.

我遇到了使用 css 溢出自动隐藏垂直滚动条的问题。我在几篇文章中阅读了使用 css 悬停伪类来实现这种行为的文章,好消息是我在某种程度上取得了成功。

I used both 'scroll' and 'auto' for the overflow-y property. With scroll it works like a charm, but with 'scroll' the problem is even if there is no need to show the scrollbar, it is visible which I feel 'auto' does very well.

我将 'scroll' 和 'auto' 用于溢出-y 属性。使用滚动它就像一个魅力,但是使用“滚动”,问题是即使不需要显示滚动条,它也是可见的,我觉得“自动”做得很好。

But again with 'auto' the problem is there is a 16px(I assume) gap at the right side. Probably it the width of the scrollbar. I wanted the full width. I used a background to explain my problem.

但是再次使用“自动”时,问题是右侧有一个 16px(我假设)的间隙。可能是滚动条的宽度。我想要全宽。我用背景来解释我的问题。

Here is the fiddle. http://jsfiddle.net/9scJE/

这是小提琴。http://jsfiddle.net/9scJE/

div.autoscroll {
    height: 200px;
    width: 400px;
    overflow: hidden;
    border: 1px solid #444;
    margin: 3em;
}

div.autoscroll:hover {
    /* overflow-y: scroll; */
    overflow-y: auto;
}

Appreciate any help.

感谢任何帮助。

回答by Explosion Pills

This actually seems like a browser bug to me, but it seems to work like you want if you add padding-right: 1pxon hover.

这对我来说实际上似乎是一个浏览器错误,但是如果您添加padding-right: 1px悬停,它似乎可以像您想要的那样工作。

div.myautoscroll:hover {
     overflow: auto;
     padding-right: 1px;
}

http://jsfiddle.net/ExplosionPIlls/9scJE/1/

http://jsfiddle.net/ExplosionPIlls/9scJE/1/

回答by Daniel

You should compensate for the scrollbar with padding.

您应该使用填充来补偿滚动条。

div.autoscroll:hover {
    /* overflow-y: scroll; */
    overflow-y: scroll;
padding-right: 16px;

}

However it is better to do this with javascript, since the scrollbar width can slightly differ between browsers. I have used this solution with success: How to calculate the width of the scroll bar?

但是,最好使用 javascript 执行此操作,因为浏览器之间的滚动条宽度可能略有不同。我成功地使用了这个解决方案:如何计算滚动条的宽度?

回答by asianGeek

::-webkit-scrollbar{
     opacity:0;
     background: transparent;
}
::-webkit-scrollbar:hover{
     opacity: 1;
}
.container:hover::-webkit-scrollbar-thumb{
     background: red;
}

回答by Eli

You can add width: 100%;when hover on the div:

您可以在将width: 100%;鼠标悬停在 div 上时添加:

 div.myautoscroll:hover {
     overflow: auto;
     width: 100%;
 }

Working Demo

Working Demo