DIV color change in CSS depending on database results?

I want to change the background color of the DIV depending on some true / false values ​​in the database used. Could this be done in CSS or am I forced to use inline CSS when it comes to this?

One of the solutions I came across is that I created several (4-5) classes that will be called, but all classes had the same CSS rules, except for the color, and that only made me think that it is redundant, but a waste of space.

I also researched and it seems you can have PHP variables in CSS. BUT, I would like to do this without creating a separate .css / .php file for the link in the header for several reasons. Is it possible?

Maybe I can better explain with some code. Here is the concept I'm trying to get to and want to know if I can do this without an external stylesheet ?:

<hml> <head> div.content { background-color: <?php echo $LegendColor; ?>; border-style:solid; border-width:2px; border-color: #000; margin: 10px 0px; } </head> <body> <?php /* After some database connection & query*/ while ($row = mysql_fetch_assoc($result2)) { $var1 = $row["db_boolean_var1"]; $var2 = $row["db_boolean_var2"]; $var3 = $row["db_boolean_var3"]; $var4 = $row["db_boolean_var4"]; if($var1 == TRUE){ $LegendColor = "#F00"; } elseif ($var2 == TRUE){ $LegendColor = "#F0F"; } elseif($var3 == TRUE){ $LegendColor = "#999"; } elseif($var4 == TRUE){ $LegendColor = "#0F0" ; } else{ $LegendColor = "#FFF"; } echo "<div class=\"content\"> </br> </div>"; } </body> </html> 
+4
source share
2 answers

Why not do

 div.content { border-style:solid; border-width:2px; border-color: #000; margin: 10px 0px; } 

and then add an extra class to the div depending on the result of db, for example.

 <div class="content <?php echo getContentClass($row) ?>"> ... </div> 

where getContentClass() is a helper function that translates these booleans into meaningful CSS classes instead of specific color values.

 function getContentClass(array $row) { return implode(' ', array_intersect_key( array( 'db_boolean_var1' => 'state1', 'db_boolean_var2' => 'state2', 'db_boolean_var3' => 'state3', 'db_boolean_var4' => 'state4' ), array_filter($row) )); } 

Then just add these CSS classes to your regular stylesheet, e.g.

 div.state1 { background-color: red; color: inherit } 

Thus, everything is cleanly separated, and you do not need to resort to built-in styles.

Edit: note that class names as shown above do not make sense. Also not so cool names like red or black, because they are associated with the presentation. Try making them related to content, for example. something like invalid, errors, paid, free, active, etc.

+3
source

You can use many classes for html elements, so you need to change the color class. The built-in class is the best solution for this.

 <element class="thing red" /> element.thing { general rules } .red { color:red; } 
0
source

All Articles