PolymerJS: Dynamically changing a CSS style

[Previously](http://blog.denevell.org/polymer-custom-element-styled-css-variables.html), we learnt how to use the shimmed CSS variables to style a custom element.

We may want to change that dynamically. And we can by using the customStyle property on the custom element.

Say we have a click listener on our element, and we want to change its '--an-ele-name-bgcolor' CSS variable.

We can get access to such property from the element (likely using event retargeting) and change the style like so.

t.clicked = function(e) {
   var tar = Polymer.dom(e).localTarget;
   tar.customStyle['--an-ele-name-bgcolor'] = 'pink';

For performance reasons, we have to call updateStyles on our component ourself.


  1. We can also dynamically alter the varibles in a CSS mixin, but only with obliterating any CSS you don't respecify from what I can tell at the moment.

Full source: index.html

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
        <link rel="import" href="bower_components/polymer/polymer.html">
        <link rel="import" href="an-ele.html">
        <style is="custom-style">
                --an-ele-name-bgcolor: purple;
        <template id="app" is="dom-bind">
            <an-ele on-tap="clicked">
       window.addEventListener('WebComponentsReady', function(e) { 
            var t = document.querySelector('#app');
            t.clicked= function(e) {
               var t = Polymer.dom(e).localTarget;
                t.customStyle['--an-ele-name-bgcolor'] = 'pink';

Full source: an-ele.html

<link rel="import" href="bower_components/polymer/polymer.html">

<dom-module id="an-ele">

        .name {
            background-color: var(--an-ele-name-bgcolor, green);
        <span class="name">hi</span>
            is: "an-ele"

polymer polymer-styles

Edit on github
comments powered by Disqus
Click me