Tips for adjusting the scrollbar in Tailwind (next.js/react)

Having trouble changing the appearance of my scrollbar in a single page application using Tailwind (react/next).

I've attempted to create custom CSS for the first div in my index file, like so:

<div className="no-scroll"> <<<<<<<--------- Adding custom css here
      <Head>
        <title>Oscar Ekstrand</title>
        <link rel="icon" href="/images/favicon.ico" />
    
      </Head>
      
      <main className="flex flex-col no-scroll">
        <section ref={heroref}>
          <Hero scrollToContacts={scrollToContacts} />
        </section>

        <section ref={offeringref}>
          <Offering />
        </section>
        <section ref={processref}>
          <WhatIDo />
        </section>

        <section ref={biographyref}>
          <CvBar />
        </section>
        <section ref={skillsetref}>
          <Skillset />
        </section>
      </main>
      <section ref={contactsref}>
        <Footer />
      </section>
    </div>

While I've successfully applied custom CSS classes to other elements like buttons using various methods, such as a "plugin-approach" or global style sheet (https://play.tailwindcss.com/zQftpiBCmf), I'm struggling to figure out how to customize the scrollbar's appearance.

Any suggestions would be greatly appreciated!

Answer №1

If you're looking to customize the scrollbar styling in Tailwind CSS, you won't find a built-in solution. However, you can leverage the various ::-webkit-scrollbar pseudo-elements to achieve the desired style.

For a hands-on experience, check out this Tailwind playground link: https://play.tailwindcss.com/5samiwyr4v.

@layer utilities {
  .scrollbar::-webkit-scrollbar {
    width: 20px;
    height: 20px;
  }

  .scrollbar::-webkit-scrollbar-track {
    border-radius: 100vh;
    background: #f7f4ed;
  }

  .scrollbar::-webkit-scrollbar-thumb {
    background: #e0cbcb;
    border-radius: 100vh;
    border: 3px solid #f6f7ed;
  }

  .scrollbar::-webkit-scrollbar-thumb:hover {
    background: #c0a0b9;
  }
}

Answer №2

yarn add -D tailwind-scrollbar

or

npm install --save-dev tailwind-scrollbar

next, include the plugin in your configuration:

plugins: [
    // ...
    require('tailwind-scrollbar'),
],

Here is a sample code snippet showcasing the use of the scrollbar utility:

<div class="h-32 scrollbar scrollbar-thumb-gray-900 scrollbar-track-gray-100">
    <div class="h-64"></div>
</div>

You can also customize scrollbar variants like so:

variants: {
    // ...
    scrollbar: ['dark']
}

If you need to modify the width of the scrollbar, you can do so in your tailwind.css file:

@layer utilities {
  .scrollbar-medium::-webkit-scrollbar {
    width: 12px;
  }
}

After customization, apply the new style to your element:

<div class="h-32 scrollbar scrollbar-thumb-gray-900 scrollbar-track-gray-100 scrollbar-medium">
    <div class="h-64"></div>
</div>

There is currently only one default style for scrollbars which is scrollbar-thin, but you can customize it further based on your needs.

Answer №3

I have successfully customized the scrollbar using a Tailwind plugin as shown below:

// tailwind.config.js

const plugin = require('tailwindcss/plugin');

module.exports = {
// ...
  plugins: [
    plugin(({ addBase, theme }) => {
        addBase({
            '.scrollbar': {
                overflowY: 'auto',
                scrollbarColor: `${theme('colors.blue.600')} ${theme('colors.blue.200')}`,
                scrollbarWidth: 'thin',
            },
            '.scrollbar::-webkit-scrollbar': {
                height: '2px',
                width: '2px',
            },
            '.scrollbar::-webkit-scrollbar-thumb': {
                backgroundColor: theme('colors.blue.600'),
            },
            '.scrollbar::-webkit-scrollbar-track-piece': {
                backgroundColor: theme('colors.blue.200'),
            },
        });
    }),
],
// ...
};

You can implement it like this:

<div class="scrollbar">
    <!-- content -->
</div>

Answer №4

/* Styling Scrollbars for Different Browsers */

/* For Firefox Browser */
.scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #000 #fff;
}

/* For Chrome, EDGE, Opera, and Others */
.scrollbar::-webkit-scrollbar {
  width: 20px;
}

.scrollbar::-webkit-scrollbar-track { 
  background: #fff;
}

.scrollbar::-webkit-scrollbar-thumb { 
  background:#000;
}

Answer №5

The latest update to TailwindCSS's documentation has introduced new styles for scrollbars using the plugin they are utilizing:

scrollbar:!w-1.5 scrollbar:!h-1.5 scrollbar:bg-transparent scrollbar-track:!bg-slate-100 scrollbar-thumb:!rounded scrollbar-thumb:!bg-slate-300 scrollbar-track:!rounded

/** @type {import('tailwindcss').Config} */
module.exports = {
  mode: 'jit',
  content: ['./src/**/*.{html,ts,tsx,js}'],
  darkMode: 'media',
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [
    // Link to the source code where these variants were added
    function ({ addVariant }) {
      addVariant(
        'supports-backdrop-blur',
        '@supports (backdrop-filter: blur(0)) or (-webkit-backdrop-filter: blur(0))',
      );
      addVariant('supports-scrollbars', '@supports selector(::-webkit-scrollbar)');
      addVariant('children', '& > *');
      addVariant('scrollbar', '&::-webkit-scrollbar');
      addVariant('scrollbar-track', '&::-webkit-scrollbar-track');
      addVariant('scrollbar-thumb', '&::-webkit-scrollbar-thumb');
    },
  ],
};

Answer №6

Enhance Tailwind's capabilities by incorporating your own foundational styles in addition to Preflight. Simply include them in your CSS file using a @layer base directive:

// Add the following code inside styles.css

@tailwind base; 
@tailwind components;
@tailwind utilities;

@layer base {
::-webkit-scrollbar-thumb{
@apply bg-transparent shadow-sm
}
::-webkit-scrollbar{
@apply w-3 bg-transparent
}
::-webkit-scrollbar-thumb{
@apply rounded-none bg-blue-400 /*customize trackbar color*/
}

}

For more information, refer to the documentation [here][1] [1]: https://tailwindcss.com/docs/preflight

Answer №7

Furthermore, in addition to the previous comment:

To implement a dark theme option, simply include the following code snippet and name it as desired:

<div className="... overflow-auto scrollbar dark:scrollbarkdark> ...

Next, make sure to add the corresponding styles in your main CSS file as detailed in the aforementioned comment.

.scrollbar::-webkit-scrollbar-track {
    background: white;
}
.scrollbardark::-webkit-scrollbar-track {
    background: black;
}
...

Answer №9

After some experimentation, I successfully implemented a solution by combining css and tailwind in my globals.css file. By using the @layer directive at the base level, the styles are applied globally across the entire website. Additionally, with the use of @apply, we can easily declare styles using tailwind classes. In this particular instance,

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  /* width */
  ::-webkit-scrollbar {
    @apply w-2
  }
  
  /* Track */
  ::-webkit-scrollbar-track {
    @apply bg-inherit
  }
  
  /* Handle */
  ::-webkit-scrollbar-thumb {
    @apply bg-pink-200 dark:bg-violet-600 rounded-xl
  }
  
  /* Handle on hover */
  ::-webkit-scrollbar-thumb:hover {
    @apply bg-violet-700
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to minimize excessive gap between two columns in Bootstrap

How can I reduce the space between two form-groups without moving the email address field with CSS left margins? When I try to make the first column smaller, it automatically wraps to the next line, but I want the email address to be closer to the phone ex ...

Navigating Next.js - Managing Imported Images from APIs

I have a situation where I am utilizing Next.js's Image component to display images retrieved from an API. However, the issue I am facing is that I do not have access to the dimensions of the images. This raises the question of how I should approach h ...

Using the React API to fetch data

Just starting out with React and APIs, I decided to fetch data from a MongoDB API. The data is being logged correctly in the console, but I'm having trouble rendering it. import React from 'react'; class Api extends React.Component { comp ...

Troubleshooting Problem with Responsive Bootstrap Navbar

I've been working on creating a menubar using Bootstrap where the logo image is centered instead of being on the left side of the bar. However, I'm facing an issue where the right links in the menu go off the screen. When I view the page with a w ...

What is the best way to link my React application with my Express API?

I've been immersed in my react app project for a while now, and I've recently delved into developing a server (using node and express) as well as planning to incorporate a database for it (MongoDB). My client-side react app has been smoothly run ...

Ways to address the dependencies problems when using npm install @types/react?

Encountering an issue with the @types/react package. This pertains to a small UI project developed on top of the nextron platform. Everything was functioning smoothly until I had to reinstall my Windows OS. Attempting to rebuild the project using yarn an ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Tips for transferring data to index.html from Fetch API

Trying to transfer data from an API to my website has been a challenging task. The structure of my directories is as follows: project > server.js | public public > index.html | styles.css A snippet of my code in server.js shows the process: ...

Enforce a restriction on the user's input value for the amount field within a React application

I'm looking to limit the user from entering more than 50000 in the input value. How can I achieve this using React? I am currently handling this on the onchange event. onPaymentAmountChanged = (e) => { let inputValue = e.target.value; if (i ...

Is it possible to display a Processing message at the beginning of a datatables table already containing data?

Within my Laravel 5.7 application, I have implemented the "yajra/laravel-datatables-oracle": "~8.0" library and found a helpful thread on customizing the processing message at this link. I adjusted the processing message styling as follows: .dataTables_pr ...

The functionality of the Bootstrap navbar-fixed-top seems to be malfunctioning

I am currently working on creating a page layout with a fixed navigation bar positioned at the top. I am aiming for a design similar to the one showcased here. Upon examining the example linked above, it appears that the content of the page begins below t ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

Tips for utilizing the "onSuccess" feature in the useQuery function of tRPC version 10?

Trying out trpc with t3 stack and looking to update a state upon successful useQuery. Encountering a TypeScript error on the frontend: Argument of type '{ onSuccess: (shoppingList: ShoppingItem[]) => void; }' is not assignable to parameter ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Include two additional elements for action in a list

In my React project, I've created a list with the following elements: Avatar Text Edit icon Delete icon I managed to set up the structure successfully up until the delete icon. Now, how can I properly add it without overlapping the edit icon? Both ...

NextJS was throwing a warning at me, while Firebase hosting was giving me an error regarding the absence of unique keys for children in lists, even though I

I've been troubleshooting this warning for quite some time, but I can't seem to resolve it. The warning reads as follows: Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using <ul>. ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...