you can define custom properties either in components to make them local or load them from StaticResource, if they are not already present on the page.
Salesforce by default loads its' properties in :root
, but you can't use :root
in LWC components.
So if you want to make property component-specific use something like this.
/* CSS */
:host {
--bgColor: green;
}
.title {
background-color: var(--bgColor);
}
If you want to make them global you need to load them from StaticResource
/* Resource.css */
:root {
--titleFontSize: 16px;
}
// component.js
import { loadStyle } from 'lightning/platformResourceLoader';
import styles from '@salesforce/resourceUrl/Resource';
// ...
connectedCallback() {
loadStyle(this, styles + 'pathtoStyle.css');
}
// ...
/* component.css */
.title {
font-size: var(--titleFontSize);
}
UPDATE
you can also get/set properties dynamically.
you can get values from apex and/or set them with JS
// controller.js
isFirstRender = true;
renderedCallback() {
if (!this.isFirstRender) {
return;
}
this.isFirstRender = false;
document.documentElement.style.setProperty('--titleColor', 'red');
const customProperty = getComputedStyle(document.documentElement)
.getPropertyValue('--titleColor');
}
/* component.css */
:host {
display: block;
color: var(--titleColor);
}