How do you change background color on td in CSS?

I am trying to change background color on table cell depending on tp1_value.
tp1_value is selected cell value from database table and it is either True or False.

How do I make this so background-color become ‘green’ on true, ‘red’ on false? Default color is grey before I click table cell which is null value.

It doesn’t seem like I can use if statement on css. 🙁

    <table class="t1">

            <tr>
                <td id="tp1"><div class="t"><label id="tp1_value"></label></div></td>
            </tr>
    </table>

#tp1_value {
        background-color: grey;
}

3 thoughts on “How do you change background color on td in CSS?”

  1. let’s say that tp1_value is changeable with any condition, so you have to set your code as per the result,

    here is a snippet shows the result in case the id is changeable between true and false.

    document.querySelector('.ftrue').addEventListener('click', function() {
    document.querySelector('label').setAttribute('id', "true");
    });
    document.querySelector('.ffalse').addEventListener('click', function() {
    document.querySelector('label').setAttribute('id', "false");
    });
    label#true {
    background: green;
    color:white;
    }
    label#false {
    background: red;
    color:white;
    }
    <table class="t1">
    
                <tr>
                    <td id="tp1"><div class="t"><label id="tp1_value">[Text]</label></div></td>
                </tr>
        </table>
        
        <button class="ftrue">True</button>
        <button class="ffalse">false</button>
    Reply
  2. You have to do that based on your server scripting language (that will talk to your db)

    For example, you would create these 2 styles:

    #tp1_green {
            background-color: green;
    }
    #tp1_red {
            background-color: red;
    }
    

    And the page would print the styles based on your server logic (ASP example below):

    <tr>
        <td id="tp1"><div class="t">
            <label id="<%if dbvalue = "green" then%>tp1_green<%else if dbvalue = "red" then%>tp1_red<%end if%>"></label>
        </div></td>
    </tr>
    
    Reply
  3. You need to use javascript to apply conditional logic.

    var tp1Cell = document.getElementById("tp1")
    var tp1Value = document.getElementById("tp1_value").html
    
    If (tp1Value === "True") {
        tp1Cell.style.backgroundColor = 'green'
    } else {
        tp1Cell.style.backgroundColor = 'red'
    }
    
    Reply

Leave a Comment