0 votes
by (360 points)
.redbg {background: red;}

<<set $red = "redbg">>

<div class= <<print $red>> >DIV WITH RED BACKGROUND</div>

How to set a CSS class as a variable?

2 Answers

0 votes
by (250 points)

The only way I know is:

.redbg {background: red;}

<<set $red = "redbg">>

<<if $red is "redbg">>
<div class="redbg">Red background</div>
<<else>>
<div>This is normal div</div>
<</if>>

 

by (250 points)
edited by

Variables can only be set with strings of text or numbers not other macros or classes of css, so when you set <<set $red = "redbg">> you are setting the variable to the letters of r.e.d.b.g. as a text string, not as a reference to your .redbg class. Here is another way:

.redbg {background: red;}
.bluebg {background: blue;}

<div class="redbg">This div was set as a red background</div>

<<timed 2s>><<addclass ".redbg" "bluebg">><</timed>>

Using the <<addclass> macro will change any class you specify.  You can set the <<addclass>> macro in a <<replace>>, <<link>> or <<timed>> macro to make the change in the passage.

more info: 
http://www.motoslave.net/sugarcube/2/docs/macros.html#macros-addclass

0 votes
by (63.1k points)

You should probably use the <<addclass>> macro for this. 

<div id="some-div">blah blah blah</div>
<<timed 10ms>><<addclass '#some-div' $red>><</timed>>

 

...