php - Changing DIV color in CSS depending on database results? -
i want change background color of div depending on true/false values in database i'm running. can done in css or forced use inline css when comes this?
one solution came had created several (4-5) classes called classes had same css rules except color , made me think redundant , waste of space.
i researched , seems can have php variables in css. without making separate .css/.php file link in header several reasons. possible?
maybe can explain better code. here concept i'm trying , want know if i'm able without 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 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>
why not do
div.content { border-style:solid; border-width:2px; border-color: #000; margin: 10px 0px; }
and add additional class div depending on db result, e.g.
<div class="content <?php echo getcontentclass($row) ?>"> ... </div>
where getcontentclass()
helper function translates these boolean values meaningful css classes instead of concrete 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 add css classes regular stylesheet, e.g.
div.state1 { background-color: red; color: inherit }
this way, cleanly separated , dont have resort inline styles.
edit: please note class names shown above not meaningful. nor classnames red or black meaningful because presentation related. try make them content related, e.g. invalid, error, paid, free, active , on.
Comments
Post a Comment