CSS Variables
CSS Variables play a central role in customizing the appearance of webforJ components. These variables store reusable values such as colors, font sizes, and spacing, that can be applied consistently across your app.
Unlike traditional approaches that relied on CSS preprocessors like SASS or LESS, CSS variables allow for dynamic styling at runtime. They reduce repetition, improve maintainability, and make stylesheets easier to read and manage.
Defining CSS variables
CSS variables are defined using a double-dash (--
) prefix, and can be scoped within any CSS selector. However, the most common practice is to define them in the :root
selector, which scopes them globally.
:root {
--app-background: orange;
}
:root
pseudo-classThe :root
pseudo-class targets the root element of the document—typically <html>
in HTML. It behaves like html
, but with higher specificity.
CSS variables can hold any string, not just valid CSS values. This flexibility is particularly useful when working with JavaScript.
html {
--app-title: webforJ;
}
Component-specific variables
To define or override a variable for a specific component, declare it within the component’s selector:
dwc-button {
--dwc-button-font-weight: 400;
}
Each webforJ component supports a specific set of CSS variables that control its appearance. These are documented under the Styling > CSS properties section for each component.
Using CSS variables
Use the var()
function to apply the value of a variable in your styles:
.panel {
background-color: var(--app-background);
}
You can also specify a fallback value in case the variable isn't defined:
.frame {
background-color: var(--app-background, red);
}
Manipulating variables with webforJ
CSS variables can be dynamically updated via webforJ API, enabling real-time styling:
// Set a CSS variable
button.setStyle('--dwc-button-font-weight', '400');
webforJ allows you to execute JavaScript on the client side using the Page or Element API. This means you can dynamically manipulate CSS variables at runtime just like you would in standard web applications.
// Set a CSS variable
const el = document.querySelector('dwc-button');
el.style.setProperty('--dwc-button-font-weight', '400');
// Get a CSS variable
const value = el.style.getPropertyValue('--dwc-font-size-m');