Search code examples
javascriptcssweb-componentshadow-dom

Understanding the basics of :host-context


I'm really lost with :host-context. :(

I watched a few videos, read the MDN page and tried to play around in VSCode to understand.

All I understood (maybe wrongly) from my tries was that with :host-context I can access a "DOM layer" between Shadow DOM and the regular, light DOM and style it.

Can someone explain :host-context to me like I'm 5 years old?


Solution

  • My understanding is that :host-context is like :host except you can pass it a selector, and it will only match if the shadow host matches that selector in the light DOM. So lets say you have a custom element my-element. You want to style this div background color: red, but only if the my-element is in an H1, because it shouldn't appear in an H1 and the red is a clear sign to the dev that they made a mistake.

    You can do this:

    :host-context(h1) { background-color: red }
    

    And the red background will only show up if my-element is a descendent of an h1.

    <h1>
      <my-element></my-element> <!-- red! warning! -->
    </h1>
    <div>
      <my-element></my-element> <!-- no red, a-ok -->
    </div>