Background image

I am trying to add a background image to my dash app:
this is my code:
import dash
import dash_html_components as html

app = dash.Dash(name)

app.layout = html.Div(style={
‘background-image’: ‘url(“diginex.png”)’,
‘background-repeat’: ‘no-repeat’,
‘background-position’: ‘right top’,
‘background-size’: ‘150px 100px’
},children = [
html.H1(‘Hello World’),
html.P(‘This image has an image in the background’)
])

app.run_server(port = 8059)

This not working

The same in HTML is working fine:

<!DOCTYPE html>

<html>

<head>

<style>

div {

background-image: url(“diginex.png”);

background-repeat: no-repeat;

background-position: right top;

background-size: 150px 100px

}

</style>

</head>

<body>

<div>

<h1>Hello World!</h1>

<p>This page has an image as the background!</p>

</div>

</body>

</html>

can anybody help?

1 Like

Create a folder called assets in the same directory as your app script, and put your image in there. Then change url("diginex.png") to url("/assets/diginex.png"). This worked when I tried it just now.

The reason is that Dash won’t serve just anything from your local filesystem (which is actually a good thing) so you have to tell it what it can serve up and where to look for those things. By default, Dash is configured to look for a folder called assets and serve up any images in there, so the easiest thing is to create the folder and save your images there.

See the section Embedding Images in Your Dash Apps in the Dash documentation for more details.

5 Likes

Thank you very much this solved it

1 Like

Hello @tcbegley!
I am a beginner and I am stuck with the image issue on Dash. I need to upload an image as a background in the header and an image in the header as a logo at the centre. I used background: url("") function and I have been trying everything: I created a folder in Documents, Downloads, Desktop and I called assets but it doesn’t work. Where exactly the asset folder should be to be served by Dash? I am unable to use any image. PLEASE HELP!!!

See the documentation here. The assets/ folder should be in the same location as your app.py script.

- app.py
- assets/
    |-- image.png

I don’t think any of these answers have actually adressed one issue - the issue is when trying to load an image using the style keyword within the .py file, not the CSS.

Has anyone been able to make this work?

html.Div(‘HELLO’,style={‘background-image’:‘url(“/assets/bgimage.png”)’,‘height’:‘100vh’})

Is it necessary to put this in the CSS file instead?

Hey @ksod, have you tried your own example? Because it works for me. Shouldn’t be necessary to put it in CSS if you don’t want to.

Hi, yeah I’ve been trying this exact example. With the quotation marks in the same format