Search code examples
htmlcsspolymerweb-component

Passing custom CSS to Polymer element


I would like to be able to pass CSS width to my custom element's shadow DOM.

The custom element, called my-list, is defined as below:

<dom-module id="my-list">
    <style>
        #container {
            width: var(width, 100%);
        }
    </style>

    <template>
        <div id="container">
            <content></content>
        </div>
    </template>

    <script>
        Polymer({
            is: 'my-list'
        });
    </script>
</dom-module>

It is used like this:

<style type="text/css">
    .medium {
        width: 500px;
    }
</style>

<my-list class="medium">
    <list-entry>1</list-entry>
    <list-entry>2</list-entry>
</my-list>

However, the 500px width is not applied; the width is still 100%.

What am I doing wrong?


Solution

  • CSS variable names need to start with --

    <dom-module id="my-list">
      <template>
        <style>
          #container {
            width: var(--my-list-width, 100%);
          }
        </style>
    
        <div id="container">
          <content></content>
        </div>
      </template>
    
      <script>
        Polymer({
          is: 'my-list'
        });
      </script>
    </dom-module>
    

    Hint: the <style> tag should be within the <template> tag (this was explained differently a while back in the docs but changed later).


    If you use Polymer features you need to add is="custom-style" for Polymer to know it needs to process (polyfill) the styles inside this style tag.

    <style is="custom-style" type="text/css">
      /* .medium { I think this should work but I fear it doesn't - haven't investigated yet*/
      :root { /*this works */
        --my-list-width: 500px;
      }
    </style>
    
    <my-list class="medium">
      <list-entry>1</list-entry>
      <list-entry>2</list-entry>
    </my-list>