Responsive custom scrollbar with CSS3 media queries
How to use custom scrollbar plugin with CSS3 media queries and switch between vertical and horizontal scrollbars according to viewport size.
In order to switch scrollbar axis on-the-fly we need the following:
- An element with content (e.g. lists) that makes sense to display vertically and horizontally (duh!)
- The CSS that’ll change the element’s dimensions and its contents via media queries
- Setting the axis option of
mCustomScrollbar
function to"yx"
and the callback functions to change scrollbar’s mouse-wheel axis on-the-fly
The markup
For this tutorial the element contains a simple unordered list
<div id="content-1"> <ul> <li>First</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>Last</li> </ul> </div>
The CSS
We’re using a mobile-first approach, meaning that all the basic CSS rules apply on the smallest viewport size and via media queries we’ll change/add CSS rules for larger size(s).
The goal is to have a narrow element with vertical scrollbar at 1024 pixels or lower and a wider element with horizontal scrollbar on higher screens.
#content-1{ width: 260px; height: 400px; overflow: hidden; padding: 10px; } #content-1 ul{ width: 230px; margin: 0; padding: 0; list-style: none; overflow: hidden; } #content-1 li{ width: 200px; height: 120px; margin: 5px; padding: 5px 10px; background: #dbf3f7; } @media only screen and (min-width: 1024px){ #content-1{ width: 80%; height: 170px; } #content-1 ul{ width: auto; } #content-1 li{ float: left; } }
The javascript
Initialize 2-axis scrollbars on the element and add onOverflowY
and onOverflowX
callbacks to change mouse-wheel axis
<script> (function($){ $(window).load(function(){ $("#content-1").mCustomScrollbar({ axis:"yx", //set both axis scrollbars advanced:{autoExpandHorizontalScroll:true}, //auto-expand content to accommodate floated elements // change mouse-wheel axis on-the-fly callbacks:{ onOverflowY:function(){ var opt=$(this).data("mCS").opt; if(opt.mouseWheel.axis!=="y") opt.mouseWheel.axis="y"; }, onOverflowX:function(){ var opt=$(this).data("mCS").opt; if(opt.mouseWheel.axis!=="x") opt.mouseWheel.axis="x"; }, } }); }); })(jQuery); </script>
By following the same pattern and inverting the @media CSS rules you can easily do the exact opposite (a horizontal scrollbar on small screens and a vertical on large ones). The custom scrollbar is responsive by default. The key is to set the axis option parameter to "yx"
when you need to switch scrollbars.
honestly resizing the browser doesn’t do jack if you measure the screen width but other than that, 5/5.
Thanks for giving the solution.!