reactjsmaterial-uijss

Material UI - How can I style the scrollbar with CSS in JS?


I really hate having to have an external stylesheet for my scrollbar stylings and I want to put it in with the rest of my styles on my root component. I have tried this...

const styles = (theme: Theme) =>
  createStyles({
    scrollBar: {
      '&::-webkit-scrollbar': {
        width: '0.4em'
      },
      '&::-webkit-scrollbar-track': {
        '-webkit-box-shadow': 'inset 0 0 6px rgba(0,0,0,0.00)'
      },
      '&::-webkit-scrollbar-thumb': {
        backgroundColor: 'rgba(0,0,0,.1)',
        outline: '1px solid slategrey'
      }
    }
  });

and then adding the class to root component div. I am using the withStyles HOC and the other styles there are being applied, so I know it is working, but I cannot figure out how to get at the scroll bar styles. Is there any way to do this?

<div className={classes.scrollBar} />

Solution

  • Since you want to do this globally, you may want to follow what CssBaseline does in it source code: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/CssBaseline/CssBaseline.js

    const styles = theme => ({
      '@global': {
        '*::-webkit-scrollbar': {
          width: '0.4em'
        },
        '*::-webkit-scrollbar-track': {
          '-webkit-box-shadow': 'inset 0 0 6px rgba(0,0,0,0.00)'
        },
        '*::-webkit-scrollbar-thumb': {
          backgroundColor: 'rgba(0,0,0,.1)',
          outline: '1px solid slategrey'
        }
      }
    });
    

    it looks like the top-level/global selector to use is @global.