Paul Paul - 11 months ago 46
CSS Question

Adding background color to element within php if-statement

I have the following code in which I want to add an element to my if statement, but I am unsure how to approach this. What I am looking to do is add a background-color to the else part of it. Within this:

else {
$status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';

So if
is not 0, I want to set background color for the class

Is there anyway I can manipulate the CSS through php like this?

foreach ($rows as $row) {
$status = $row['status'];
if ($status == 0) {
$status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
else {
$status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
$goal_date = $row['date'];
$fixed_goal_date = fixDate($goal_date);
$html = "";
$html .= '<div class="goal-box" id="comment-'.$row['id'].'">';
$html .= '<div class="goal-box-left">'; //added
$html .= '<div class="goal-post-status">'.$status_img. '</div>';
$html .= '</div>'; //added
$html .= '<div class="goal-box-right">'; //added
$html .= '<div class="goal-post-title">'.$row['title']. '</div>';
$html .= '<div class="goal-post-date">'.$fixed_goal_date. '</div>';
$html .= '<div class="goal-post-description">'.$row['description']. '</div>';
$html .= '</div>'; //added
$html .= '</div>';

Answer Source

Separate the logic - add a CSS class based on the status then set the colours in the stylesheet.

$class = $status != 0 ? 'status-nonzero' : '';

$html .= '<div class="goal-box-right ' . $class . '">';


.goal-box-right.status-nonzero { background-color: #foo }

Advantage is keeping the style logic in the CSS where it belongs and away from the code that's generating the HTML.