Search code examples
csspolymer-1.0web-componentshady-dom

Document styling affecting local DOM when using Polymer 1.0 Shady DOM


The following illustrates this issue with a trivial example I have prepared and pushed to a github repo.

I created a custom element "x-menu" (in /x-menu.html) with styling rules for the light DOM. In practice, my use case for doing so is to use CSS variables and mixins to define colors, font-stacks, etc. to be used in the document and custom elements.

I have a custom element defining document styling (in /demo/index.html) as described in the relevant part of the Polymer 1.0 dev guide, which defines some typography rules for my pages.

This works fine with native Shadow DOM in Chrome.

However, when using Shady DOM the document styling resolves to style definitions which have higher specificity than the styling in the x-menu element. This is now it appears in the Styles stack of Chrome's developer tools:

ul:not([style-scope]):not(.style-scope), p:not([style-scope]):not(.style-scope) {
    font-size: 12px;
    color: red;
}

.container.x-menu ul, .container.x-menu p {
    font-size: 30px;
    color: green;
}

I understand there are some limitations with Shady DOM and Shadow DOM polyfill (webcomponents.org simply says a known limitation is "CSS encapsulation is limited."),

There are two workarounds I can think of, neither of which is very practical:

  1. Add a CSS class to every light DOM node (which you can see in the demo page)
    • This is not practical because a user of the custom element has to remember this and defeats the CSS encapsulation goal.
  2. Apply a CSS mixin to the local style definition. When processed by Shady DOM, the CSS has higher specificity than "custom-style" at the document level.
    • This becomes more cumbersome and adds unnecessary overhead in developing, maintaining, and processing the CSS.

I am looking for any ideas for a suitable workaround for this issue. Worst-case, I would like to put the onus on the element developer rather than the user of the element.


Solution

  • Seems like a possible limitation of the style shim. Polyfilling CSS is hard! I'd recommend filing an issue on the Polymer repo with this demo.