htmlcssshadow-domweb-contentwebcontent

How to use parent CSS from Shadow DOM


I have css from parent application that I want to use inside a web-component made by shadow dom. I don't want to copy css from parent aplication to web-component, but right now, the web-component can't see the parent application css, how can I do that?

parent app:

<style>
.pretty-button {
  color: green
}

</style>
<body>
  <button class="pretty-button">Got It</button>
  <custom-element></custom-element>
</body>

web-component made by shadow dom: 

<!--doesn't work because the shadow dom can't use parent css class-->
<body>
  <button class="pretty-button">Got it from shadow dom</button>
</body>

Solution

  • Shadow DOM is protected from outside CSS. This is by design.

    TL;DR:

    If you want the outside CSS to affect DOM inside the shadowRoot of a custom element then you need to either:

    1. Use a <slot> or
    2. Copy the CSS into the shadowDOM

    Here are three answers I have given on similar questions: