Hello 👋I am Hamza Ali, one of my developers! I’m happy to share with you a simple yet effective method for customizing scrollbars in React, Next.js apps. By adjusting the CSS, you may create a smooth and visually pleasing scrollbar that improves the user experience. Let’s plunge in!
The goal
We want to create a narrow, custom-colored scrollbar for our pick drop-down component. This customization will be compatible with several browsers, including Chrome, Edge, Safari, and Firefox.
Step-by-Step Guide
1. Defining CSS Variables
First, let’s define our custom colors for the scrollbar. We’ll use CSS variables to make it easy to adjust these colors later.
:root {
--scroll-bar-color: white;
--scroll-bar-bg-color: white;
}
2. Custom Scrollbar Styles
Next, we’ll create a class .selectscroll
to apply our custom scrollbar styles. This will ensure that only the targeted elements have the customized scrollbar.
.selectscroll {
scrollbar-width: thin; /* For Firefox */
scrollbar-color: var(--scroll-bar-color) var(--scroll-bar-bg-color); /* For Firefox */
}
.selectscroll::-webkit-scrollbar {
width: 1px; /* For Webkit browsers like Chrome, Safari, and Edge
}.selectscroll::-webkit-scrollbar-track {
background: var(--scroll-bar-bg-color);
}.selectscroll::-webkit-scrollbar-thumb {
background-color: var(--scroll-bar-color);
border-radius: 2px;
border: 1px solid var(--scroll-bar-bg-color);
}
In this CSS:
scrollbar-width: thin;
andscrollbar-color: var(--scroll-bar-color) var(--scroll-bar-bg-color);
are used for Firefox.- The
::webkit-scrollbar
pseudo-elements are used to style the scrollbar for WebKit browsers (Chrome, Safari, and Edge).
3. Applying the Styles in Your Component
Now, let’s add style classes to our React component. We’ll use a div
to wrap our Select
component and apply the .selectscroll
class to it.
const YourComponent = () => {
return (
<div style={{ position: "relative", marginBottom: 24, height: 100, width: "100%", background: 'white' }}>
<div style={{ position: 'absolute', width: '100%', height: '680px', overflowY: 'scroll' }} className="selectscroll">
<Select
className={}
label={}
onChange={}
options={}
style={{
marginBottom: ‘20px’
}}
searchOptions
/>
</div>
</div>
);
}export default YourComponent;