Carlos Martinez Carlos Martinez - 1 year ago 79
Sass (Sass) Question

render components with user selected colors

I have a form where I ask users a color for an specific project, it is being stored as a string in my model that represents a hex value (e.g:


What I'd like is to be able to render page components using this color and avoid using inline styles like this:

<h2 style="color: <%= project.color %>;"><%= project.client.upcase %></h2>

As the colors will be predefined (there might be a list of 10 predefined colors) I was thinking I could store the
names instead. However, doing this I would have to maintain the list of colors in more than one place:

  • I would have to validate that the color class specified by the user is in the list, so I'd need the list in my backend code

  • I would need the list of colors defined in my SASS

  • And probably would also need the list of colors in my javascript for the color picker

Another problem I have when storing hex values is when I want to use a different shade of the color:

<div class="progress" style="background-color: <%= project.color %>">
<div class="progress-bar" style="width: 40%; background-color: <%= project.color %>;">

In this case I would like the first div to have a lighter version of the color, I would use sass ligthen for this, but can't do it using inline styles.

I looked into this question but I won't like to recompile my sass per request as that would be very slow.

I would be using this color in a lot of components, what is a flexible way of achieving this?

Answer Source

So, I opted for storing class names in the database, in my markup it would look like this:

<div class="project project-color-<%= project.color %>">
  <div class="element">a div</div>
  <div class="another">another div</div>

Then in my sass, I'm storing a map of colors:

$project-colors: (
  pomegranate:          $pomegranate,
  razzmatazz:           $razzmatazz,
  purple-heart:         $purple-heart,
  cool-blue:            $cool-blue,
  deep-sky-blue:        $deep-sky-blue,
  iris-blue:            $iris-blue,
  gossamer:             $gossamer

And then I create these classes dynamically:

.project {
  @each $name, $color in $project-colors {
    &.project-card-#{$name} {
      .element {
        background-color: $color;

      .another {
        color: $color;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download