user8887707
user8887707

Reputation:

use the name of the classes to give a specific color using mixin in scss

I'm starting to practice with sass and I want to set any color with the percentage of red, green and blue in the class. So, the class name color-50-10-60 means 50% red, 10% green and 60% blue, the numbers can only vary in quantities of 10 in 10, so there can only be numbers like 10, 20, 30, 40... up to 100, if I change the numbers that have the name of the class must change color, I know that I must use mixin to get it but I just do not understand how to do to achieve the goal. Any help?

Upvotes: 0

Views: 672

Answers (1)

ReSedano
ReSedano

Reputation: 5060

I think it's impossible (technically possible, but useless) to create a specific class for every single RGB color.

We have to start from words. SASS is a PREPROCESSOR, i.e. occurs before everything: before your CSS, your HTML, your JAVASCRIPT... and he (SASS) can't logically know what you'll write in your HTML, but only imagine (CSS attr() has potential, but also big limitations https://caniuse.com/#search=attr() ...).

If you write something like this <div class="color-50-10-60">, in your CSS there must already be the definition of that class. So, when you write your SCSS before you create that <div>, you have to imagine you'll use that class.

But, you know, you can create a limited range of colours (10-20 color's classes with a specific mixin, if you really want). Certainly you can not create them all, because RGB have 16,777,216 possible color values and... it's crazy to think about creating 16 million classes (^_^;)

You have then to create first your <div class="color-50-10-60">, and then read those values creating a CSS class to manage them: to do this, you can use javascript. This is your way to achieve the goal. :)

But, I know, you want a CSS solution. Then... use <div style="color:rgb(50,10,60);">: it's cross-browser and it works very well! ;)

EDIT 1

After your edit, this is a possible solution for you: that works with a range of colours (as I said in the comments, it works with loops with 3 variables... but for me it is crazy! :-) ):

@for $i from 1 through 10 {
    @for $j from 1 through 10 {
      @for $k from 1 through 10 {
      .color-#{$i*10}-#{$j*10}-#{$k*10}{
        color:rgb($i*10,$j*10,$k*10);
      }
    }
  }
}

I created a sassmeister for you:

Upvotes: 1

Related Questions