Make scrollbars only visible when a Div is hovered over?
div {
height: 100px;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
div:hover {
overflow-y: scroll;
}
<div>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>
Would something like that work?
The answer with changing overflow have a bunch of issues, like inconsistent width of the inner block and triggering of reflow.
There is an easier way to have the same effect that would not trigger reflow ever: using visibility
property and nested blocks:
.scrollbox {
width: 10em;
height: 10em;
overflow: auto;
visibility: hidden;
}
.scrollbox-content,
.scrollbox:hover,
.scrollbox:focus {
visibility: visible;
}
.scrollbox_delayed {
transition: visibility 0.2s;
}
.scrollbox_delayed:hover {
transition: visibility 0s 0.2s;
}
<h2>Hover it</h2>
<div class="scrollbox" tabindex="0">
<div class="scrollbox-content">Hover me! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere velit, repellat voluptas ipsa impedit fugiat voluptatibus. Facilis deleniti, nihil voluptate perspiciatis iure adipisci magni, nisi suscipit aliquam, quam, et excepturi! Lorem
ipsum dolor sit amet, consectetur adipisicing elit. Facere velit, repellat voluptas ipsa impedit fugiat voluptatibus. Facilis deleniti, nihil voluptate perspiciatis iure adipisci magni, nisi suscipit aliquam, quam, et excepturi!</div>
</div>
<h2>With delay</h2>
<div class="scrollbox scrollbox_delayed" tabindex="0">
<div class="scrollbox-content">Hover me! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere velit, repellat voluptas ipsa impedit fugiat voluptatibus. Facilis deleniti, nihil voluptate perspiciatis iure adipisci magni, nisi suscipit aliquam, quam, et excepturi! Lorem
ipsum dolor sit amet, consectetur adipisicing elit. Facere velit, repellat voluptas ipsa impedit fugiat voluptatibus. Facilis deleniti, nihil voluptate perspiciatis iure adipisci magni, nisi suscipit aliquam, quam, et excepturi!</div>
</div>
Another feature of this method is that visibility
is animatable, so we can add a transition to it (see the second example in the pen above). Adding a transition would be better for UX: the scrollbar won't appear immediately when hovered just while moving along to another element, and it would be harder to miss the scrollbar when targeting it with mouse cursor, as it won't hide immediately as well.