top of page

How to dynamically set custom CSS properties in LWC?

Jul 27, 2021
2 min read

Hi! 🙂

Imagine, as a developer, you’ve a use case where you’re developing a custom modal LWC component and you’d like to make it flexible so that you can easily adjust the height of the modal.

One (and relatively the easier) way of doing this is by using in-line CSS, and here’s how it will look(somewhat)

/* JS file */

import { LightningElement, api } from 'lwc';export default class CustomModalExample extends LightningElement { @api height; /* This property is exposed via the XML file. */ get modalStyling() { return 'height:' + this.height; }}

/* Html file */

<template> <!-- Modal Container --> <div style={modalStyling}> <!-- Modal --> </div></template>

This’d work fine, however, using in-line CSS is NOT a best practice and it’s generally advised to use CSS file to style your component. But then, the question arises that how can you use variables in your file CSS files and set their value at runtime.

So if we refactor the code of the aforementioned example , it’d look like this.

/* CSS File */

.modal-container { height : var(--modalHeight, 500px);}

/* JS File */

import { LightningElement, api } from 'lwc';export default class CustomModalExample extends LightningElement { @api height; /* This property is exposed via the XML file. */ /* A lifecycle hook that is Called after every render of the component. */ renderedCallback() { this.initCSSVariables(); /* JFYI, use a flag if you only want to run this logic on first render of the component. */ } initCSSVariables() { var css = this.template.host.style; css.setProperty('--modalHeight', this.height); }}

/* Html file */

<template> <!-- Modal Container --> <div class="modal-container"> <!-- Modal --> </div></template>

This way you can prevent yourself from writing in-line CSS, and if you’re wondering what is var() in the CSS file, you can checkout the MDN documentation.

JFYI, this solution came from here.

Hope you find this one useful! Catch you in the next one! ✌ And thank you for being an awesome reader! Subscribe to this blog for receiving all the latest updates straight to your inbox. 🙂

 
 
 

Comments


bottom of page