Black Lives Matter. Please consider donating to Black Girls Code today.

Apply some css style of all dash components

I’m building an interface using Dash and am pretty impressed with the available components so far. One problem I’m having, however, is achieving my desired formatting, without the code becoming very ugly and bloated.

For example, I’d like to minimise white space around various input fields (e.g. daq.NumericInput) and can achieve this using CSS styles. At present, I manually set the className for every field component I use.

However, if there some sort of global flag I can set? i.e. for ALL daq.NumericInput components, use some style?

Or alternatively, is there a way to make a style apply to all components that are children of some frame?


Not really.

Sometimes you can inspect the underlying HTML that is generated and then apply CSS styles (via a stylesheet) to the class names that might be part of the underlying component (rather than applying your own class names). However, styling components in that way could break in the future as the underlying class names as part of the markup aren’t part of the official API.

If I apply the same set of parameters to the same set of components, I’ll frequently write my own function that supplies my preferred set of styles. I’ll put all of these functions into their own function called e.g.

def Dropdown(**kwargs):
    style = kwargs.pop('style')
    style_with_defaults = dict({'width': '50px'}, **style)
    return dcc.Dropdown(style=style_with_defaults, **kwargs)

Then, instead of using dcc.Dropdown, I’ll use components.Dropdown. This is an approach that works not just with CSS but with supplying your own defaults & logic to any components that you are using.

Thanks, that’s a good idea and clean solution.