0

How do I introduce theming with CSS variables?

I am building an NPM package that is supposed to have basic values, which are defined like

:root { --primary: red; }

when I import those values and afterwards declare

:root { --primary: blue; }

for some variables there is a change, for some, not. I thought I might take advantage of DOM precedence like

:root > * { --primary: blue; }

but then none of the theme styles get applied. I assume because my dependant styles like this are also declared on root level in the npm package:

:root { --header-primary: var(--primary); }

So how do you do it the right way?

Phil
  • 7,065
  • 8
  • 49
  • 91
  • `:root > *` --> this will target one element which is the body element – Temani Afif Apr 02 '20 at 11:45
  • @TemaniAfif ok, let me rephrase the question: is there a way for me to provide a basic theme in an npm package, so the customer only has to override a few values, but not the whole palette of style definitions? The linked answer does not tell anything about it, it just says it doesn't work and says how to override values further down in the dom hierarchy. I don't want to override values in components though, I want to do it globally. – Phil Apr 02 '20 at 12:06
  • you cannot, this what the duplicate is explaining. If you evaluate variable inside root then it's dead Variable should not be evaluated inside root but at component level OR you change everything at root level – Temani Afif Apr 02 '20 at 12:08
  • I think this should be possible somehow, at least with sass. Can't I declare custom variables via a function and pass default values from the npm package and override values provided by myself (as the customer) and the function will use the override value only if it exists? – Phil Apr 02 '20 at 12:14
  • setting `:root { --primary: blue; }` should work for you if you correctly add it at the end. Share a more complete example and show us how you are adding the styles – Temani Afif Apr 02 '20 at 12:17
  • I consume the npm package like this ```@import "~@some/npm/styles"; // contains :root { --primary: red; } @import "local/custom/overrides"; // contains @mixin override colors { --primary: blue; } :root { @include override-colors }``` For some colors there is an override, for others not, it feels like random – Phil Apr 02 '20 at 12:25
  • and what is the rendred CSS? share it here: https://jsfiddle.net/ – Temani Afif Apr 02 '20 at 12:27

0 Answers0