Search code examples
javascripthtmlcssweb-componentshadow-dom

Styling content inserted in the Shadow DOM


I have this example:

http://codepen.io/dbugger/pen/IuDxw

Where I have an insertion point inside the Shadow DOM and I try to apply an style to it, making it disappear. But the image is still visible. I suspect there is some principle I haven't undestood propely from the Web Components.

Can someone explain me what am I doing wrong?


Solution

  • The trick is that the image is not, as kkemple mentioned, part of the Shadow DOM, but rather the Light DOM, which means it's not directly accessible from inside the component. It's user provided content, like the parameters passed into a class constructor in an OOP language. If at all possible, then, the user should provide their own styles to go with it.

    That being said, there are definitely valid use cases where the component author wants to style user-provided content. Hiding certain parts of the user-provided markup based on attributes on the host, events (clicks), etc. is definitely one of those. In that case, wrap the <content> element in a Shadow DOM element and hide that:

    <template>
      <style>
        .image {
          display: none;
        }
      </style>
      <div class="image">
        <content></content>
      </div>
    </template>
    

    http://codepen.io/anon/pen/rCGqD

    On a side note: It is technically possible to apply styles directly to Light DOM elements, but be aware that in many cases this is considered leaking implementation details to the outside world. If the first solution works, use that instead.