Conditional formatting of an html element

Hello dear Dash wizards,

I know there is a conditional formatting property for dash data table but is there a way to change the text color and background color of a html.P or html.H4 element based on a condition in a callback function with Dash?

For example, it could be something like this (very schematically):
def function():
if temperature > 25:
background text color for temperature = green
background text color for temperature = red

Thanks for your help!


In principle you can use the “style” prop in a callback. Here’s a tiny example:

from dash import Dash, html, dcc, Output, Input, State

app = Dash(__name__)

app.layout = html.Div(
        html.H4(id="heading", children="A Heading")

    Output("heading", "style"),
    Input("input", "value")
def update_style(value):
    return {
        "color": value

if __name__ == "__main__":

Please also note that the style will be entirely overwritten by the callback, so if you have extra parameters when you define the component in the first place, you should pass also the State and combine the current style with the new one.

1 Like