Divyanshu Rawat
Divyanshu Rawat

Reputation: 4721

Polymer way of changing css using js

I am from angular, react background getting started with polymer.

I have a polymer class lets say myClass having this template.

<div  id="[[x]]">

Here x is property defined in property getter.

  static get properties() {
    return {      
      x: {
        type: Number,
        value: 200
      },
}

Here if I set value of x dynamically using chrome dev tools console, like myClass.x = '5' it works fine and output will be.

<div  id="5">

same goes true for other html attributes like

   <div  width="[[x]]">
   <div  height="[[x]]">

but now consider a case scenario that I want to give margin property dynamically to my div in the same way that I am doing with id, width, height how can I do it in Polymer?

In angular we can do this.

<div [style.marginTop.px]="marginTop">

Let me know your thought in polmer way od doing things.

Upvotes: 4

Views: 85

Answers (2)

lvilasboas
lvilasboas

Reputation: 76

It can also be achieved using CSS variables:

:root {
    --custom-margin-top: 20px;
}

div {
    margin-top: var(--custom-margin-top);
}

And via JS you can:

updateMarginTop(marginTop) {
    this.updateStyles({
        '--custom-margin-top': `{marginTop}px`
    });
}

Upvotes: 1

Divyanshu Rawat
Divyanshu Rawat

Reputation: 4721

I got it, can be achieved by doing something like this.

<div style$="margin:{{ x }}px;">

Upvotes: 2

Related Questions