Question

I'm trying to style the text in the shadow dom without success. The only thing is that I want to do it from outside the shadow DOM. An other important thing, the Shadow dom styling should only apply to the shadow dom inside a 'bar' element. Here is my test code:

<!doctype html>

<html>
  <head>
    <style>
      :host(bar) span:first-child {
        text-transform: uppercase;
        color: green;
      }
    </style>
  </head>

  <body>
    <bar></bar>

    <script>
      var bar = document.querySelector('bar');
      var root = bar.createShadowRoot();
      root.innerHTML = '<span>bar</span><span>foo</span>';
    </script>
  </body>
</html>

And a bonus question, what exactly does

:host(bar:host) { ... }

do ?

Was it helpful?

Solution

The shadow DOM specification is currently still in development, most of its functionality is radically changing from one moment to the next.

To style a shadow DOM element from the outside it depends on if your browser relies on the (outdated) peusdo-element exposure or the new css shadow dom selectors ^^ (cat) and ^ (hat) If the browser supports the new syntax, you can simply enter an elements shadow dom using the hat (^) selector, or if you wish to cross all shadow boundaries, you can use the cat (^^) selector to do so.

If the browser does not yet support it, you need to expose the element you wish to style as a pseudo-element of its parent by adding the pseudo attribute to it, <shadow-element peusdo="myname" />, and then reference that pseudo element in your css shadow-host::myname

As to your 'bonus' question, you are referencing the shadow host element, but only if the shadow host is a <bar> element, if you omit the second :host you are referencing a shadow host that is a <bar> element or has one as its ancestor.

Do note that because the API is in constant development, the above information may not remain reliable beyond more then a month or so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top