How to create style scoping for arbitrary content with Polymer / Web Components

217 views Asked by At

I am trying and failing to create a simple web component just for style scoping purposes.

The idea is that I would define a component - say <scoped-style> - which @imports a stylesheet so that any instance of <scoped-style> will scope the imported stylesheet for me. I just want to separate styles within elements and without.

So far I haven't even been able, using Polymer, to create a component which applies <style> based styles to the arbitrary content any instance might contain. It appears that content which goes in <content></content> can only be styled using

:host ::content [selector] {
  /* shadowy styles */
}

This is extremely limiting and wrecks my @import plan too.

Here's the component definition so far:

<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="scoped-style">
    <style>
        p {
            background: red;
        }
    </style>
    <template>
        <div>
            <p>Paragraph outside content (below) which _does_ go red</p>
            <content></content>
        </div>
    </template>
    <script>
        Polymer({
            is: "scoped-style"
        });
    </script>
</dom-module>

And here's the usage I intend:

<scoped-style>
  <p>This paragraph should _also_ go red, but doesn't.</p>
</scoped-style>

Many thanks!

1

There are 1 answers

1
stopsatgreen On

No, that’s right. On the Guide to Styling Elements it notes:

The distributed [element - <p>, in your case] remains [black] because it’s logically still in the parent page and therefore matching scoped-style > p. It’s simply being rendered elsewhere (over in Shadow DOM land).