Change styles of elements dynamically with custom properties?

For example, you can change the color ink

in paper-tabs

by changing --paper-tab-ink: var(--accent-color);

. Is it possible to change the value of CSS custom properties dynamically in a similar way to how you can switch class or change style in JS?

+3


source to share


2 answers


There are different ways to do this, but the simple answer is to use the Polymer.updateStyles () method after making changes to the class.

For example, let's say your styles are:

<style>
.yellow x-example {
  --light-primary-color: #fdd85f;
}
.red x-example {
  --light-primary-color: red;
}
</style>

      



and you want the component to use styles in the .red class. You just add it as you normally would in javascript, then remember to also use this function to actually update the page.

<div class="yellow" onclick="this.className='red'; Polymer.updateStyles()">
  <x-example></x-example>
</div>

      

+1


source


Yes, first get your custom item object. Then get a customStyle object. Add style to this object. Then run element.updateStyles ();

       t.clickListener= function(e) {
           var t = Polymer.dom(e).localTarget; //retarget if needed
           t.customStyle['--the-color-etc'] = 'pink';
           t.updateStyles(); // mandatory for the CSS variables shim
       };

      



See docs

+1


source







All Articles