Showing scrollbars only when mouseover div

后端 未结 6 1964
猫巷女王i
猫巷女王i 2020-12-31 02:22

Given this div:

How can I make the scrollbars visible only when the mouse is

6条回答
  •  礼貌的吻别
    2020-12-31 03:05

    The answer with changing overflow have a bunch of issues, like inconsistent width of the inner block, triggering of reflow, the need to have extra code for deal with paddings and without disabling keyboard (and, possibly, other) interactions when not hovered.

    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 {
      visibility: visible;
    }
    

    Here is a pen with a working example: http://codepen.io/kizu/pen/OyzGXY

    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.

提交回复
热议问题