Today while working on my first Wordpress theme, I ran into a situation where I wanted to control the color of a navigation bar that is styled with a dynamically added CSS class.
My initial thought was to output the hex code of the color chosen in the customizer in the inline style of my element like this:
<my-element style=”background-color: <?php echo get_theme_mod(‘setting_element_color’); ?>”></my-element>
The only problem is that I’m trying to change the color of my element when scrolled by adding a class on-scroll using jQuery.
How then could I change the color that’s applied by the dynamically added class with the Wordpress customizer’s color picker?
It was at this moment that I had remembered playing around with CSS custom properties (also called CSS variables) some days before and thought I would give it a shot.
After a quick Google about CSS custom properties, the idea looked do-able. So now instead of setting the color directly inline like we did above, we output our customizer control color to a custom property
<my-element style=”--bg-color: <?php echo get_theme_mod(‘setting_element_color’); ?>”></my-element>
--bg-color variable lives on the element and can be accessed in our CSS or SCSS.
Looking at our CSS Rule now we have something like
and voilà! Now we can control the color of our element styled with our dynamically added class!