Search code examples
csspolymer-1.0stylingweb-component

Custom style mixin for deep selectors


I've just hit a wall with custom-style. Unfortunately it seems that any mixins and variables are applied to descendants of elements matched in the Light DOM. On the other hand the :root selector applies the vars and mixins to all custom elements.

Isn't there a middle ground where it would be possible to style eg. any custom element that has a given class etc? For example I would like to have

<style is="custom-style">

   my-element.important {
      --border-color: red;
   }  

</style>

To set the variable for each instance of <my-element> withe the given class. Currently it only works for elements in the Light DOM (for document level style) and Local DOM (when setting variables/mixins inside other element). It also doesn't work for anything like :root my-element or :root /deep/ my-element or html /deep/ my-element

I've prepared a reproduction on Plunker.


Solution

  • The solution is quite simple, as pointed out by @lozandier and Karl on Polymer's Slack channel.

    For document-level styles the property groups must be wrapped in with :root selector

    <style is="custom-style">
    
       :root {
          my-element.important {
             --border-color: red;
          }
       }  
    
    </style>
    

    And for style inside element it's necessary to use :host instead

    <dom-module>
       <template>
          <style>
    
             :host {
                my-element.important {
                   --border-color: red;
                }
             }  
    
           </style>
       </dom-module>
    </template>