Arms crossed picture of James Auble
CodePen Screenshot of CSS Var Used

Color Picker Wordpress Control with a Dynamically Added CSS Class

PublishedApr 27th, 2019

Update: I can't for the-life-of-me remember why I decided to use this method instead of just toggling classes and creatively using CSS selectors. But i'll leave this post up anyway because it is ONE way to do it.

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>

Now our --bg-color variable lives on the element and can be accessed by any of its descendant elements.

Looking at our CSS Rule now we have something like

.dynamic-class {
 background-color: var(--bg-color);

and voilà! Now we can control the color of our element styled with our dynamically added class!

Scrolldown Icon