In this post, We’ll learn how to show a scrollbar in CSS only when you hover over a box or area. We’ll look at different ways to do this. Have you ever wanted the scrollbar to appear only when needed or wondered how to hide it? We’ll cover that too.
To display a scrollbar in CSS only when hovering over an element, you’ll initially set the overflow
property of that element to hidden
. When the element is hovered over, you’ll change the overflow
to scroll
. This simple technique ensures the scrollbar is neatly tucked away, only appearing when the user places their cursor over the designated area.
Different Ways to Show Scrollbar on Hover
Method 1: Using Pure CSS
To show the scrollbar only when the div is hovered over, you can use the following Code.
<div class="hover-scrollbar">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum...Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum...
</div>
HTMLThis method sets the overflow
property of the div
to hidden
by default, hiding the scrollbar. When the div
is hovered over, the overflow-y
property is set to scroll
, making the vertical scrollbar visible.
div {
height: 100px;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
div:hover {
overflow-y: scroll;
}
CSSOutput:
Method 2: Using Visibility Property to Show Scrollbar on Hover
Another approach is to use the visibility
property in combination with nested blocks:
This method ensures that the scrollbar’s visibility is toggled without causing a reflow, which can sometimes lead to flickering or other layout issues.
<div class="visibility-scrollbar">
<div class="visibility-scrollbar-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum...Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum...
</div>
</div>
HTMLdiv {
height: 100px;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
div:hover {
overflow-y: scroll;
}
CSSMethod 3: Webkit Browsers Specific Solution
For webkit browsers like Chrome and Safari, you can style the scrollbar and make it transparent by default, then change its color on hover.
body::-webkit-scrollbar {
background-color: transparent;
width: 10px;
}
body:hover::-webkit-scrollbar-thumb {
background-color: black;
}
CSSNote: It’s essential to test these methods across different browsers to ensure compatibility and consistent behavior. Some solutions might work better in specific scenarios or design requirements than others.