Search code examples
cssshadow-dom

css variables :root vs :host


Just starting with webdevelopment (coming from android) in my project I tried to assign variables as in many tutorial is mentions with help of ":root" :

:root {
  --accentColor: #20a8d8;
  --primary: #96a1a5;
  --secondary: #415a72;
  --bgColorrr:#1e2e38;
}

But that did not work at all. After changing it to ":host" it work though - can someone please explain what is the reason behind :root not working?

May be worth mention: I used that on my custom component (Angular 5) and I'm using CoreUI (in case that may effect some CSS)


Solution

  • You're talking about Shadow DOM. Elements can get a new kind of node associated with them. This new kind of node is called a shadow root. An element that has a shadow root associated with it is called a shadow host. The content of a shadow host isn’t rendered; the content of the shadow root is rendered instead. There's this thing called Style Encapsulation.

    SHADOW DOM

    Also I would suggest avoiding the use of :root. I know the docs say to use :root and technically I think that's fine to do at the document level, but you are using a framework maybe there is a conflict inside of the Shadow DOM and cause a bug. Avoiding :root all together might just be a good habit to get into. @pb4now correct me if I'm totally wrong about stuff.

    Here's more info about Shadow DOM and read more about Angular Style Components. Hope it helps.