.   .   .
ūüí° Sick of moving pixels around with CSS? Partner with our team. We'll build the user interfaces. You build the back-ends. Escape CSS work today!
.   .   .

So recently I’ve been mulling over how to utilize color options I created for a client in the WordPress admin.¬† We use SASS¬†to compile our theme’s CSS but really wanted to utilize the color options we created with Redux Framework.¬† Say you wanted a user to be able to define¬†their header background color.¬† You could use something like Redux Framework or add an option to the WordPress Customizer. The problem though, is I want to use the option in my stylesheets. I think I’ve come up with a slick and simple way to do this by utilizing CSS Variables.

Two things to note about CSS Variables:

  1. They’re native to the browser.
  2. They live in the DOM.

You declare them like this:

:root {
  --default-color: #fff;
}

And use them like this:

.my-page-header {
  color: var(--default-color);
}

For our WordPress theme, all we have to do is:

Step 1. Echo our¬†users’ styles into your markup.

<?php
// Set a variable and give it a default.
$header_bg = ! empty( $theme_options['header_bg_color'] )
  ? $theme_options['header_bg_color']
  : '#FFF';
?>
<!-- echo the variable our script tag -->
<style>
/* css variables */
body { --header-bg-color: <?php echo $header_bg ; ?>;  }
</style>

 

Step 2. Use the variable in our SASS.

.header {
  background-color: var(--header-bg-color);
}

Notes:

  • Browser support is great but if you need to support I.E. I’d suggest not using this for core parts of your style.
  • The W3 School tutorial¬†on CSS Variables is a good place to check out if you haven’t used CSS variables before.