How to make div scrollable sideways using mousewheel?

Viewed 283

I want to scroll inside a div when I hover it instead of scrolling the whole page (with mouse wheel). This works usually for scrolling for overflowY (up and down) but not for overflowX (sideways)

I dont know if its doable with only CSS or if it needs JavaScript or jQuery

I have made an example with a div that has an overflow of X axis with a scroll, and when u point at it and use your scroll wheel it scrolls the page instead of the div that you are hovering.

.parent {
    background: red;
    height: 100px;
    width: 100px;
    display: flex;
    overflow-x: scroll;
}

.child {
    background: blue;
    border: 1px solid black;
    margin: 3px;
    height: 30px;
    width: 50px;
    flex-shrink: 0;
}

body {
    height: 200vh;
}
<body>
    <div class="parent">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>

1 Answers

You can do it by rotating the container element 90deg. Check this example:

HTML

<div class="horizontal-scroll-wrapper squares">
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
  <div>item 7</div>
  <div>item 8</div>
</div>

<div class="horizontal-scroll-wrapper  rectangles">
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
  <div>item 7</div>
  <div>item 8</div>
</div>

CSS:

::-webkit-scrollbar{width:2px;height:2px;}
::-webkit-scrollbar-button{width:2px;height:2px;}

div{
  box-sizing:border-box;
}

body {
  background: #111;
}

.horizontal-scroll-wrapper{
  position:absolute;
  display:block;
  top:0;
  left:0;
  width:80px;
  max-height:500px;
  margin:0;
  background:#abc;
  overflow-y:auto;
  overflow-x:hidden;
  transform:rotate(-90deg) translateY(-80px);
  transform-origin:right top;
}
.horizontal-scroll-wrapper > div{
  display:block;
  padding:5px;
  background:#cab;
  transform:rotate(90deg);
  transform-origin: right top;
}

.squares{
  padding:60px 0 0 0;
}

.squares > div{
  width:60px;
  height:60px;
  margin:10px;
}

.rectangles{
  top:100px;
  padding:100px 0 0 0;
}
.rectangles > div{
  width:140px;
  height:60px;
  margin:50px 10px;
  padding:5px;
  background:#cab;
  transform:rotate(90deg) translateY(80px);
  transform-origin: right top;
}

Check other examples here: https://css-tricks.com/pure-css-horizontal-scrolling/

Related