MichielB MichielB - 1 month ago 6
CSS Question

How to get OS X like scrollbars on all platforms

On OS X scrollbars in the browser have native platform styling. I'd actually like to have this style also on other platforms. I know it's possible on Chrome to customize the look of the scrollbars. Is there any way I can achieve the "OS X look" using CSS on other platforms in Chrome?

Answer

Here is some code that I made a while back. You can take it and customize the scroll bar any way you want.

Try it in this jsfiddle: http://jsfiddle.net/wLD49/

HTML:

<div class="container">
    <div class="scrollable">
        <div class="content">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sagittis blandit lectus tempus aliquam. Aenean tempor libero odio, in gravida dui laoreet vitae. Duis porttitor, sem id convallis rhoncus, enim dolor volutpat nibh, vel sollicitudin arcu tortor eget elit. Vestibulum eu eros in ante rutrum porttitor. Quisque volutpat faucibus est, cursus suscipit nisi tincidunt sit amet. Proin leo odio, aliquam ac rutrum eget, rutrum quis dui. Nam tincidunt, diam at fringilla rhoncus, mi lacus faucibus sem, eu dapibus nunc felis ac nisl.
        </div>
        <div class="scrollbar"></div>
    </div>
</div>

CSS:

.container {
    width: 200px;
    height: 100px;
    overflow: hidden;
    border: 1px solid blue;
    position: relative;
}

.scrollable {
    overflow-x: hidden;
    overflow-y: auto;
    width: 100%;
    height: 100%;
    padding-right: 30px;
}

.content {
    /* 10px for the scroll bar plus some extra spacing */
    padding-right: 12px;
}

.scrollbar {
    width: 8px;
    height: 25px;
    background-color: lightblue;
    border-radius: 4px;
    position: absolute;
    right:0;
    top: 0;
}

.scrollable:hover .scrollbar {
    background: blue;
}

JavaScript:

var scrollables = document.getElementsByClassName('scrollable');
scrollables[0].addEventListener('scroll', scrolled);
function scrolled(e) {
  var content = this.getElementsByClassName('content')[0];
  var scrollingRange = content.offsetHeight - this.offsetHeight;
  var scrollingRatio = this.scrollTop / scrollingRange;

  var scrollbar = this.getElementsByClassName('scrollbar')[0];
  var scrollbarRange = this.offsetHeight - scrollbar.offsetHeight;
  scrollbar.style.top = String(scrollingRatio * scrollbarRange) + 'px';
  console.log(scrollingRatio, scrollbarRange);
}