green_meep green_meep -4 years ago 127
CSS Question

Accessing classes of a div in SCSS

I just got into SCSS. Apologies if it has been asked before, but nothing I could find quite matched what I wanted to do.

I have an .erb view that dynamically assigns classes to a particular div. For example, I might have something like this:

<div class="red blue green">Hello world!</div>

Is there a way to access ALL the classes of the div so I can do something like this:

@each $c in CLASSES {
$g: $g, $c;
linear-gradient(to bottom right, $g);
//would be equivalent to linear-gradient(to bottom right, #F00, #0F0, #00F);

Answer Source

Sass is a CSS preprocessor meaning it compiles into CSS and since CSS itself doesn't know what HTML exists or how it's being used, it can't be done. You should rethink how you are writing your CSS and possibly go with an approach similar to:

.gradient-rgb { linear-gradient(to bottom right, #F00, #0F0, #00F) }
.gradient-gbr { linear-gradient(to bottom right, #0F0, #00F, #F00) }
.gradient-brg { linear-gradient(to bottom right, #00F, #F00, #0F0) }

If you follow this approach, then you'd be able to use your Sass map to generate classes with some effort. You may also consider using JavaScript if generating so many possibilities isn't feasible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download