How to mutate CSS custom property color with CSS-in-JS?

Viewed 895

Suppose I have the following code with emotion's css`` prop:

<div css={css`
  background: var(--bg);
`}>

But I would like to darken the background of this div.

Using sass this would be simple with the darken() function, but I don't think it is possible to use sass in emotion?

Another option would be to use a javascript darken function, e.g. like the one from polished.js:

import { darken } from "polished";

<div css={css`
  background: ${darken(0.2, var(--bg))};
`}>

However, this is not possible either, since a CSS custom property like var(--bg) is not accessible in the javascript ${ } scope.

Is there any simple, straightforward solution to solve this?

2 Answers

For the darken() the closest I can think of is to use brightness() MDN Link

<div css={css`
  filter: brightness(80%);
`}>

It can help ;)

document.querySelector('button').addEventListener('click', () => {
  document.body.style.setProperty('--color', 'blue')
})
:root {
  --color: red;
}

body {
  background: var(--color)
}
<button>TEST</button>

Related