DEV Community

Discussion on: What would you like to know about CSS?

Collapse
 
sjellen profile image
SJellen

I’m working on a dark mode and it’s going well with css var() but I’m trying to have different background-image() for light and dark. But I can’t seem to figure it out.

I’ve got a work around now using and opacity but it’s not very clean.

Thanks

Collapse
 
mr_eis profile image
Marius Eisenbraun

I guess, you try to set the background-image with a custom property like:

:root {
  --backgroundimage: http://example.com/bg-image-light.jpg;
}

And later try to set the image with

body {
  background-image: url(var(--backgroundimage));
}

is that correct?

Custom Properties behave different than variables in e.g. JS.

In CSS custom properties, you need to store a value, that is a valid CSS value.

So this should work:

:root {
  --backgroundimage: url('http://example.com/bg-image-light.jpg');
}

@media (prefers-color-scheme: dark) {
  :root {
    --backgroundimage: url('http://example.com/bg-image-dark.jpg');
  }
}

body {
  background-image: var(--backgroundimage);
}

I hope, I could help you with your problem!
Of not, please explain a bit more details and add a code example.