How To Use Css Variables (Custom Properties) With Examples
CSS variables, also called custom properties, let you store a value once and reuse it everywhere. They are declared with two dashes and read with the var() function.
Declare and use a variable
css">:root {
--lotgrafix-color: orangered;
--lotgrafix-radius: 8px;
--lotgrafix-space: 20px;
}
.lotgrafix-button {
background: var( --lotgrafix-color );
border-radius: var( --lotgrafix-radius );
padding: var( --lotgrafix-space );
}
Fallback value
The second argument of var() is used when the variable is not defined.
.lotgrafix-box {
color: var( --lotgrafix-text, #333 );
}
Override a variable in a specific section
Variables follow the cascade, so a child can redefine a value for itself and its descendants.
.lotgrafix-dark {
--lotgrafix-color: #111;
--lotgrafix-text: #fff;
}
Change a variable with JavaScript
document.documentElement.style.setProperty( '--lotgrafix-color', 'royalblue' );
Use a variable in WordPress
Add the variables to your theme stylesheet or print them from PHP so a setting in the admin can change them.
php">function lotgrafix_print_css_variables() {
$color = get_theme_mod( 'lotgrafix_color', '#ff4500' );
echo '<style>:root{--lotgrafix-color:' . esc_attr( $color ) . ';}</style>';
}
add_action( 'wp_head', 'lotgrafix_print_css_variables' );
November 3, 2026


