23

I want to feed a CSS stylesheet or a <style> block into a Python Dash app. I've attempted to do both below, but neither works for me. The app loads fine, but the text remains black, not green.

import dash

from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from flask import send_from_directory



# define the app
app = dash.Dash()

app.head = [html.Link(rel='stylesheet', href='./static/stylesheet.css'),
    ('''
    <style type="text/css">
    h1 {
        color:green;
    }
    </style>
    ''')]

app.layout = html.Div(html.H1('Hello World!'))


if __name__ == '__main__':
    app.run_server(debug=True)

and inside ./static/stylesheet.css is a file with only this:

h1{
  color:green;
}

I've tried having just the stylesheet or just the <style> tag but neither of those turns the h1 tag green either.

Here is the research I've done to try to solve my issue:

https://github.com/plotly/dash/pull/171

https://dash.plot.ly/external-resources

https://github.com/plotly/dash-recipes/blob/master/dash-local-css-link.py

The only thing I haven't tried (that those links suggest) is to load from an external link (CDN). However I want to be able to load this app offline so that isn't an option.

2
  • Maybe it's about you declare this css first, and it's conflict with <style> tag. Commented Jun 13, 2018 at 19:30
  • dash.plotly.com/external-resources Dash supports adding custom CSS or JavaScript in your apps. Create a folder named assets in the root of your app directory and include your CSS and JavaScript files in that folder. Dash automatically serves all the files that are included in this folder. By default, the URL to request the assets is /assets, but you can customize this with the assets_url_path argument to dash.Dash. Important: For these examples, you need to include name in your Dash constructor. That is, app = dash.Dash(name) instead of app = dash.Dash(). Commented Dec 23, 2022 at 13:32

4 Answers 4

14

Local assets (.css, .js)

Starting from Dash v0.22, you would include local CSS files as follows

  1. make a assets folder in the same directory as your app.py. Put all your .cssand .js files there.

  2. Initialize the app object by giving the __name__ as the first argument; use app = dash.Dash(__name__) instead of app = dash.Dash(). (reasoning)

  3. Now Dash will automatically load your CSS and JS files. To force a correct loading order (especially important with CSS), it is recommended to name your files as 01_first.css, 02_some_customization.css, .. 25_load_this_last.css. (the loading order is always alphanumerical)

Note: Your custom CSS will be included after the Dash component CSS (source).

Inline CSS

For inline CSS, you may use the style parameter of the html.Component.

  • Give the CSS as a python dictionary
  • Use camelCase keys; text-align -> textAlign, etc.

For example:

import dash
import dash_html_components as html

app = dash.Dash(__name__)
app.layout = html.Div(
    [html.H1('Demo'), html.H3('Text')],
    style={
        'textAlign': 'center',
        'border': '1px solid red',
    },
)
Sign up to request clarification or add additional context in comments.

Comments

6

This is part of a project I did and it worked for the style

app.layout = html.Div(
style={'backgroundColor': 'black'},
children=[
    html.H1('html code')])

1 Comment

This would be great if I only had one or two Div components, but my actual project is rather large and it would be much cleaner to declare these CSS properties in a more global way (thus the stylesheet).
4

If you look at the dash-recipies on GitHub it gives you the syntax for using a local css file. The only thing that I needed to change to make this work was in the @app.server.route. Instead of:

@app.server.route('/static/<path:path>')

I used:

@app.server.route('/static/<path>')

2 Comments

AFAIK this one doesn't work. I'll try to dump everything into my /assets dir and see what happens.
@NicholasHumphrey correct. Starting with version 0.22 the assets directory is used for external css. See the Dash docs dash.plot.ly/external-resources
4

You are not serving the css. The right way is to add following lines to your app.py

app = dash.Dash()
server = app.server
app.config.suppress_callback_exceptions = True
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True

and serving your css folder using the following flask code, add it to your index.py

@app.server.route('/assests/<path:path>')
def static_file(path):
    static_folder = os.path.join(os.getcwd(), 'assests')
    return send_from_directory(static_folder, path)

This will serve everything under assests folder. Now suppose you have internal folder like css, fonts. You can refer your css using the following.

app.layout = html.Div([
    html.Div([
        dcc.Location(id='url', refresh=False),
        html.Link(
            rel='stylesheet',
            href='/assests/css/bootstrap.css'
        ),
        html.Link(
            rel='stylesheet',
            href='/assests/css/styles.css'
        )
    ]),
    html.Div(id='page-content'),

])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.