jss how to change opacity for a color

Viewed 44230

Currently I am using the following code to add a color to an element using jss.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

I would like to know if exist a function to add opacity based on colortheme.colors.red.

example smt like: backgroundColor: color(theme.colors.red, .05),

9 Answers

Material UI has a colorManipulator utility file, which includes an alpha function:

import { alpha } from '@material-ui/core/styles/colorManipulator';

/**
 * Sets the absolute transparency of a color.
 * Any existing alpha values are overwritten.
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
 * @param {number} value - value to set the alpha channel to in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

{
    backgroundColor: alpha(theme.colors.red, 0.5)
}

For Mui v5:

import { alpha } from "@mui/material";

Alternatively, you can add the color library from npm for color manipulation:

import Color from 'color';

{
    backgroundColor: Color(theme.colors.red).alpha(0.5).string()
}

Assuming you don't already have the alpha channel defined in the color, you can also do:

backgroundColor: theme.colors.red + '00' 

This will set alpha channel to 0, thus transparent. You can append any value between '00' to 'ff'

I found a solution using

 backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),

Some of these answers are referencing deprecated Material-UI functions. The current preferred approach is to use alpha:

import { alpha } from "@material-ui/core";

...
                 // yields rgba(255,255,255,0.85)
backgroundColor: alpha(theme.palette.background.paper, 0.85) 

for MUI v5 this seems to work:

import { alpha } from '@mui/material';

...

MuiContainer: {
      styleOverrides: {
        root: {
          '&.MuiContainer-asideWithImage': {
            backgroundColor: alpha(MY_COLOR, 0.78),
          },
        },
      },
    },

...

Another possibility is:

import color from "color"

const themeColorsRed = color
  .rgb(theme.colors.red)
  .array()

Then you can do:

{
  backgroundColor: `rgba(${themeColorsRed}, 0.05)`,
}

For what it's worth, an 8 digit hex code works too

const styleSheet = theme => ({
  root: {
     backgroundColor: '#ffffff80',
  },
})
Related