0
static get styles() {
    const width = window.innerWidth
    const height = window.innerHeight
    return css`
        :host{
            display: block;
        }
        .my-img{
            max-width: ${width}px;
            max-height: ${height}px;
        }
    `
}

I wrote this CSS in a web component, it works.

However, when the browser window resizes, the CSS can not change automatically.

How can I enforce it to re-calculate after window resize?

zzzgoo
  • 1,974
  • 2
  • 17
  • 34

1 Answers1

1

You can use expressions in styles but with some caveats.

Static styles apply to all instances of an element. Any expressions in your CSS are evaluated and included once, then reused for all instances.

unsafeCSS is available for use.

if you want to inject any variable or non-literal into a css string, you must wrap it with the unsafeCSS function.

class MyElement extends LitElement {
  static get styles() {
    const mainWidth = 800;
    const padding = 20;   

    return css`
      :host { 
        width: ${unsafeCSS(mainWidth + padding)}px;
      }
    `;
  } 
}

There is a big security warning with that though:

⚠️ Only use the unsafeCSS tag with trusted input. To prevent LitElement-based components from evaluating potentially malicious code, the css tag only accepts literal strings. unsafeCSS circumvents this safeguard.

abraham
  • 46,583
  • 10
  • 100
  • 152