tetchi blog

Tetchi's blog about life and stuff

Shopify Theme Settings: Assigning colours dynamically using SASS

Last week I attended CSS Conf in Florida, and one of the coolest things I learned there was a technique that Tim Hettler shared in his presentation (his awesome presentation can be found here). The technique involved using SASS to dynamically assign colors to a text depending on the background-color of the button.

So I thought to myself, “hmm… now that we can use SASS in Shopify themes, I wonder if I can somehow tie this technique into Shopify’s Theme Settings…?”. Lo and behold, it worked like a charm! I think this could be really useful to prevent users from unknowingly choosing unreadable text (ex: white text on white background).

Here’s a quick video demonstration:

The text colour changes depending on the selected colour of the background. No more unreadable text!

The code for it fairly simple. It is based off this part of Tim’s presentation. In a nutshell, what we’re doing here is checking the lightness of the selecting theme setting colour ({{settings.btn_colour }}), and assigning either #333 or #fff for the text colour depending on the value of the lightness. Here’s a quick example:

/* assigning color selected thru theme settings to variable */
$color: {{settings.btn_colour}};

/* function for checking the lightness of theme setting color */
/* if lightness is below 50, apply #333, else apply #fff */

@function get-button-color( $color ) {
  @return if( lightness( $color ) > 50, #333, #fff );

/* apply colors*/
  color: get-button-color($color);

Hope this was helpful! Shoutouts again to Tim Hettler for showing me this technique :)


Post a comment