Development

Dynamic Colors using CSS Variables and a Tiny Bit of Javascript (drupalSettings)

Tanner Heffner, Developer
#Front-end Development | Posted

The Short of It:

First, what do I mean by dynamic colors? I’m referring to a color defined by a content editor, a color that the design system doesn’t necessarily know about beforehand.

CSS Variables are great, and supported in most modern browsers, except for IE11. Calling IE11 a modern browser feels dirty, but that’s neither here nor there.

For this demo, we’ll be using Drupal’s Color field to define the colors of elements on a given page. In practical terms, we have a taxonomy vocabulary called “Category”. Each category term can define a color.

When a given content type references a category term, that category’s color field output will be preprocessed & added to drupalSettings. Once available as a drupalSetting, it can easily be assigned to a CSS variable, using a couple lines of javascript.

That CSS Variable, once defined, will trickle down to the components that need it, thanks to the power of… cascading style sheets.

The Long of It:

Drupal Fields

First things first, we’re gonna make sure we have a color to reference, and a node that uses it. So we have a taxonomy term with a color field (machine name: field_color). We also have a content type with that takes an optional reference to that taxonomy term’s vocabulary (machine name: field_category).

Drupal Preprocessing

Now in the preprocess, we need to extract the color field value from that entity reference, and attach it to the drupalSettings object. We can do this like so, in my_module.module:

  1. /**
  2.  * Implements hook_page_attachments_alter().
  3.  */
  4. function my_module_page_attachments_alter(&$page) {
  5. // Makes the section color value available to javascript for live-updating.
  6. $node = \Drupal::routeMatch()->getParameter('node');
  7. if ($node && $node instanceof NodeInterface) {
  8. $category = $node->get('field_category')->entity;
  9.  
  10. if (isset($category)) {
  11. $color = $category->field_color->color;
  12.  
  13. $page['#attached']['drupalSettings']['my_module']['page_color'] = $color;
  14. $page['#attached']['library'][] = 'my_module/sections';
  15. }
  16. }
  17. }

If we’re on a node, we check for the category field, and if that reference exists, we grab the hex string value from the color field. That gets assigned to the drupalSettings object. We also attach a js library that makes the dynamic value available to our stylesheet.

That library looks like this, inside of my_module.libraries.yml:

  1. sections:
  2. version: 1.x
  3. js:
  4. js/sections.js: {}
  5. dependencies:
  6. - core/jquery

We’ll come back to the JS in a bit, once we’ve actually set up how our CSS variables should be used.

CSS Setup

CSS Variables (aka CSS Custom Properties) are a cool “new” feature that bring the concept of variables to CSS natively. They cascade and inherit as other CSS rules do, and so CSS Variables should be defined in a selector that sets their scope. We’re interested in a global scope, because these colors need to be available to many components, so I set them on the :root selector. The body element would also be global scope, but I have other body-specific styles there, and I like the separation of concerns.

  1. // css variable set at :root for overriding section colors
  2. // based on the value of the Category taxonomy.
  3. :root {
  4. --section-color: $c-blue;
  5. }

We set a default color for the variable so that if a category isn’t referenced on a node (or if a user has javascript disabled), there’s still a default color.

I’ll only be covering how one component (a hero) can use this CSS var, but it’s the same concept for all components that need a dynamic color.

relevant portion of code:

  1. /**
  2. * Hero with a solid blue background instead of an image.
  3. */
  4. &--solid {
  5. background: $c-blue;
  6. background: var(--section-color);
  7.  
  8. ...
  9.  
  10. .hero__cta {
  11. background-color: $c-blue;
  12. background-color: var(--section-color);
  13. border: $border-thin solid $c-white;
  14.  
  15. &:hover {
  16. color: $c-blue;
  17. color: var(--section-color);
  18. background-color: $c-white;
  19. }
  20. }
  21. }

You’ll notice that I’ve duplicated some rules for colors. This is purely to satisfy IE11 and is not necessary if you don’t need to support it. This project did, so it was necessary. Because browsers drop CSS rules they don’t support, IE ignores the second declaration and falls back to the first rule without problems. Browsers that do support CSS variables (e.g. the rest of them), read both rules and use the last-defined, which happens to be our desired CSS variable. Everyone’s happy.

JS Connection

The final piece we need to make this all work as intended is updating the initial CSS variable declaration to be our desired color.

  1. :root {
  2. --section-color: $c-blue;
  3. }

We can do this in a few short lines of javascript, like so:

  1. (function pageColors($, Drupal) {
  2. Drupal.behaviors.setPageColor = {
  3. attach: function getPageColor(context, settings) {
  4. if (settings.my_module) {
  5. if (settings.my_module.page_color) {
  6. // Grabs the page color value set in my_module_page_attachments_alter().
  7. const pageColor = settings.msk_content.page_color;
  8.  
  9. // Set root CSS variable to page color. Page elements that need to be color-coded
  10. // use this variable and helper classes to ensure correct color applications.
  11. document.documentElement.style.setProperty('--section-color', pageColor);
  12. }
  13. }
  14. }
  15. }
  16. }(jQuery, Drupal));

Tada! Now we have some dynamic connectivity between our drupal Color field and our stylesheets. If you don’t need to support IE11, you’re done at this point. If you do need to support IE11… you’ll need a few more lines of javascript, as all the elements that should be receiving dynamic colors don’t have any clue about the CSS Variable! So we’ll have to hard code them as part of this function. Using our previous hero example, the complete function looks something like this:

  1. (function pageColors($, Drupal) {
  2. Drupal.behaviors.setPageColor = {
  3. attach: function getPageColor(context, settings) {
  4. if (settings.my_module) {
  5. if (settings.my_module.page_color) {
  6. // Grabs the page color value set in my_module_page_attachments_alter().
  7. const pageColor = settings.msk_content.page_color;
  8.  
  9. // Set root CSS variable to page color. Page elements that need to be color-coded
  10. // use this variable and helper classes to ensure correct color applications.
  11. document.documentElement.style.setProperty('--section-color', pageColor);
  12.  
  13. // IE11 can't read css variables at all: https://caniuse.com/#search=css%20variables
  14. // So we hard color any items that need it.
  15. const isIE = '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style;
  16. if (isIE) {
  17.  
  18. $('.hero--solid').css('background', pageColor);
  19. $('.hero--solid .hero__cta')
  20. .css('border', '3px solid ' + pageColor)
  21. .css('color', pageColor)
  22. .hover(function() {
  23. // mouseenter
  24. $(this).css('color', '#ffffff');
  25. $(this).css('background-color', pageColor);
  26. }, function() {
  27. // mouseleave
  28. $(this).css('color', pageColor);
  29. $(this).css('background-color', '#ffffff');
  30. }
  31. );
  32. }
  33. }
  34. }
  35. }
  36. }(jQuery, Drupal));

Not the cleanest, but that’s IE for you. This could be cleaned up further to use string interpolation and fat arrows, if you have babel working on this file. If not, simple string concatenation is still the way to go, because IE will error on it otherwise. Maybe someday we can leave IE behind, but this post is not that day.

Anyways, that’s all there is to it. Thanks for reading!

Tanner Heffner

Tanner Heffner

Developer