Using CSS to Create Custom Scrollbar Thumb
Why do this?
When creating an HTML5 web app that supports dynamic rebranding, UI elements need to be recolored from a stylesheet. Using a linked or embedded graphic or .svg will not provide the highest level of instant customization. Solve this by drawing the UI controls using a stylesheet. Make sure the designer has a clear idea of what is visually possible using this technique. Generally rounded rectangles, linear gradients and drop shadows are all good.
I worked from a layered Photoshop file providing dimensions, radii, gradient color range and shadow effect. You can try an automated converter to get the CSS output but I did the work manually in a self-contained pairing of HTML and CSS files.
Create an HTML 5 file and add a div with a class name. I named mine thumbPreview.html and the div class “thumb”. I then put a CSS link in the head, and named it “thumb.css”. You can put all the css inside the HTML in a <style></style> section and keep it in one file, but I want to be able to switch the CSS so I linked to it. Divs nest from back to front: if you think of them as layers, the outermost div is the background. I added some divs to make a series of thin lines that are like grips – since they are inside the thumb they are insdie the thumb div.
Next I created the CSS file and put in @charset “utf-8”; in first line and a comment about what the file is used for. I copied and pasted the shadow and gradation styles, used the PSD comp for dimensions, and used margins and padding to space and locate the grips.
Here it is in a jsFiddle:
I refreshed a page I had already created using the custom scrollbar to see the new CSS-based thumb appear in place of the png version. I realized that I had used the offset property to shit the png graphic so that it was centered over the trackbar – I would have to move the div in the stylesheet to recenter it. This was accomplished by added a margin-left to the thumb.
I renamed all divs to have the mCSB_ prefix to follow convention and informally namespace everything in case another developer decided to create a “thumb” class.
I still hadn’t addressed horizontal scrolling. This was handled via CSS Sprites before. You can see what it looks like without making any changes by changing the horizontalScroll attribute to true near the bottom of the html in the jsFiddle above.
Back to thumbPreview.html and thumb.css to create the horizontal variant. since mCSB scrollbar uses a class modifier to make the horizontal version, I followed suit using .mCSB_horizontal class name.
Most of the changes to make the horizontal version was swapping values between the vertical and horizontal for placement. Gradation and shadows stay the same. Some margin values had to change to allow the “grip” elements to stack horizontally.