4

In React, is there a way to set border color opacity while using an imported theme color?

For example if my css includes: borderBottomColor: theme.palette.primary.main with theme being imported by Material UI using makeStyles can I somehow add an opacity to this?

I know in rgb format you can do something like borderBottomColor: rgba(255, 0, 0, 0.5) so is there a way to do something similar with a theme color?

Dan O
  • 6,022
  • 2
  • 32
  • 50
  • **See Also**: [how to change opacity for a color](https://stackoverflow.com/q/47268652/1366033) – KyleMit Oct 20 '21 at 18:19

1 Answers1

3

an alpha value can be added in the end of the theme color in this way:-

borderBottom:`${theme.palette.primary.main+'77'} 1px solid`

value can be provided from 00 to ff


Another way is to use material-ui's colorManipulator utility function from directory

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

and use this as like this:-

borderBottom : `${fade(theme.palette.primary.main, 0.5)} 1px solid`

Fade accepts two values.

/**
 * Set 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()
 * @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
 */

Here is the working example:- https://codesandbox.io/s/agitated-chaum-924

Rajiv
  • 3,346
  • 2
  • 12
  • 27
  • Both options worked great. Thanks so much! – Eric Russell Nov 30 '20 at 04:26
  • **FYI** - [`fade` is deprecated](https://github.com/mui-org/material-ui/blob/v4.12.3/packages/material-ui/src/styles/colorManipulator.js#L203-L229) and you can/should user `alpha` instead – KyleMit Oct 20 '21 at 18:36