Python dash Div full page background image - python

Sorry i'm very new to dash, css, html coding.
i'm using Dash on Python and i would like a simple full page background with an image.
i'm using this CSS: https://codepen.io/chriddyp/pen/bWLwgP.css
i tried to use different CSS (https://necolas.github.io/normalize.css/8.0.1/normalize.css) beacuse i read it was a margin problem but it didn't work
i've read a lot of discussion about this issue but i wasn't able to fix it for my purposes
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__,
external_stylesheets = external_stylesheets)
app.title = "Q"
colors = {'background': '#ffffff',
'bg_home': '#666666',
'text': '#ffa500',
'background_plot': '#cccccc',
'text_plot': '#000000'}
app.config['suppress_callback_exceptions']=True
image = 'url(https://c.wallhere.com/photos/a1/fc/1920x1080_px_Albert_Einstein_Formula_mathematics_physics_science_Special_Relativity-549404.jpg!d)'
app.layout = html.Div(
className='row',
style={
'verticalAlign':'middle',
'textAlign': 'center',
'background-image':image,
},
children= [
html.Div(
id='Username',
style={'textAlign': 'center',
'verticalAlign':'middle',
},
children= [
html.H3('Login',
style={'textAlign': 'center',
'color':'orange',
'fontWeight': 'bold',
},
),
html.Div(
className='row',
children=[
dcc.Input(id = 'user',
style={'margin-top':20},
type='text',
placeholder='Username'
)
]
),
html.Div(className='row',
children=[
dcc.Input(id = 'psw',
style={'margin-top':20},
type='text',
placeholder='Password'
)
]
),
html.Div(className='row',
children=[
html.Button('Login',
id='log',
style={'background-color':'white',
'color':'black',
'margin-top': 20,
'textAlign':'right'},
),
]
)
])
]
)
if __name__ == '__main__':
app.run_server(debug=True,host='0.0.0.0',port=8050)
i'm not gettin error but i just get 1/3 (more or less) of the page with background image and login Div, the rest of the page completely white.
I just would like a full page with background image and login in the center
Thank you all

In css body tag defines the document's whole body and the div is a part of it, there are two ways to get this working.
Make the div to cover the entire page and set the image to the div
Refer here:
Making a div that covers the entire page
Modified bit of code,
className='row',
style={
'verticalAlign':'middle',
'textAlign': 'center',
'background-image':image,
'position':'fixed',
'width':'100%',
'height':'100%',
'top':'0px',
'left':'0px',
'z-index':'1000'
},
Modify the body tag in theexternal_stylesheet to have the property background-image,
body {
'background-image' : url(url!d);
}

There are 2 ways to get this done:
Note: Is is a good practice to create a folder 'assets' in the program's root directory, and place your image inside it.
Method-1:
app.layout = html.Div([ ...fill your children here... ],
style={'background-image': 'url(/assets/image.jpg)',
'background-size': '100%',
'position': 'fixed',
'width': '100%',
'height': '100%'
})
Method-2:
app.layout = html.Div([ ...fill your children here... ],
style={'background-image': 'url(/assets/image.jpg)',
'background-size': '100%',
'width': '100vw',
'height': '100vh'
})

Related

Additional elements inline with Dash's dcc.Tabs?

For my Dash app, I want to create a navigation bar that has links to the different pages but also additional stuff, e.g. the currently logged in user, and logos and stuff.
However, I unfortunately cannot use pages (Like in the "Navbar" example in dbc) since the WebApp has to be hosted as a single-url app inside another tool. My only option is to got with dcc.Tabs.
However, it looks to me like dcc.Tabs forces a newline behind the Tabs. I tried different things to prevent that, but nothing seems to be working. The best I got so far is the example below. How do I make it so that the text is in the same row as the Tabs element?
tabs_styles = {
'height': '44px', "width": "49%", "display":"inline-block"
}
app.layout = html.Div(children=[
html.Div(children=[
dcc.Tabs(id="tabs-styled-with-inline", value='tab-1', children=[
dcc.Tab(label='Page1', value='tab-1', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label='Page2', value='tab-2', style=tab_style, selected_style=tab_selected_style),
], style=tabs_styles)]),
html.Span(children=[
" Logged in as ",
html.Strong(id="username")
], style = tabs_styles),
html.Div(children=[
# Distance to header:
html.Hr(),
html.Div(id='tabs-content-inline')
])
])
Your inline style should be applied to the parent div of your Tabs component. I made some small modifications here (look at tabs_container_styles):
tabs_styles = {"height": "44px"}
tabs_container_styles = {"width": "49%", "display": "inline-block"}
app.layout = html.Div(
children=[
html.Div(
children=[
dcc.Tabs(
id="tabs-styled-with-inline",
value="tab-1",
children=[
dcc.Tab(label="Page1", value="tab-1"),
dcc.Tab(label="Page2", value="tab-2"),
],
style=tabs_styles,
)
],
style=tabs_container_styles,
),
html.Span(
children=[" Logged in as ", html.Strong(id="username")], style=tabs_styles
),
html.Div(
children=[
# Distance to header:
html.Hr(),
html.Div(id="tabs-content-inline"),
]
),
]
)
Set the parent_style property of your Tabs component instead of the style property and move your Span component to be a child of the div containing your Tabs component.
parent_style (dict; optional): Appends (inline) styles to the top-level parent container holding both the Tabs container and the content container.
style (dict; optional): Appends (inline) styles to the Tabs container holding the individual Tab components.
https://dash.plotly.com/dash-core-components/tabs
MRE
from dash import Dash, html, dcc
tabs_styles = {"height": "44px", "width": "49%", "display": "inline-block"}
app = Dash()
app.layout = html.Div(
children=[
html.Div(
children=[
dcc.Tabs(
id="tabs-styled-with-inline",
value="tab-1",
children=[
dcc.Tab(
label="Page1", value="tab-1", style={}, selected_style={}
),
dcc.Tab(
label="Page2", value="tab-2", style={}, selected_style={}
),
],
parent_style=tabs_styles,
),
html.Span(
children=[" Logged in as ", html.Strong(id="username")], style=tabs_styles
),
]
),
html.Div(
children=[
# Distance to header:
html.Hr(),
html.Div(id="tabs-content-inline"),
]
),
]
)
if __name__ == "__main__":
app.run_server()

Aligning 2 html.Divs of text next to each other in Plotly Dash

I am trying to place 2 Div elements side by side, without luck. I have been following
https://community.plotly.com/t/horizontally-stack-components/10806 and
https://medium.com/analytics-vidhya/dash-for-beginners-dash-plotly-python-fcd1fe02b749 guides on using width<50% and 'display': 'inline-block' but without luck.
If you look at attached pictures, it looks like the block that is supposed to go to the right, actually does, until i update the page by choosing a song in the list to show the lyrics on the left, then it pushes the recommendations to the bottom. Any ideas?
My code looks like this:
html.Div([
html.Div(id="lyrics",style={'width': '50%', 'display': 'inline-block'}),
html.Div([
html.H6(id="recommendations",children="Recommendations:"),
html.H3(id="songsbysameartist",children='Songs by the same artist:',
),
html.H6(id="sameartistrecommendations",
),
html.H3(id="songsfromotherartists",children='Music from other artists that you might also like:',
),
html.H6(id="otherartistrecommendations",
)
],
style = {'width': '30%', 'display': 'inline-block'})
])
edited code would look like this:
html.Div([
html.Div(id="lyrics",style={'width': '50%', 'display': 'inline-block'}),
html.Div([
html.H6(id="recommendations",children="Recommendations:"),
html.H3(id="songsbysameartist",children='Songs by the same artist:',
),
html.H6(id="sameartistrecommendations",
),
html.H3(id="songsfromotherartists",children='Music from other artists that you might also like:',
),
html.H6(id="otherartistrecommendations",
)
],
style = {'width': '30%', 'display': 'flex'})
])
since the bottom style is connected to the parent Div above recommendations as far as I can tell.
I found the solution:
I believe the error is in the structure. Parent Div needs to have "display":"flex" while the 2 children Div elements have "display":"inline-block".
Correct code ended up like this:
html.Div([
html.Div([
html.Div(id="songandartist",style={'display': 'flex',"fontSize" : 40,"marginBottom":50}),
html.Div(id="lyrics",style={'display': 'flex'}
)
],style={'width': '49%', 'display': 'inline-block'}),
html.Div([
html.Div(id="recommendations",children="Recommendations:",style={"fontSize" : 40,"marginBottom":50,'display': 'flex'}),
html.Div(id="songsbysameartist",style={"fontSize" : 27,'display':'flex'},children='Songs by the same artist:',
),
html.Div(id="sameartistrecommendations",style={"marginBottom":50,'whiteSpace': 'pre-line','display': 'flex'}
),
html.Div(id="songsfromotherartists",style={"fontSize" : 27,'display': 'flex'},children='Music from other artists that you might also like:',
),
html.Div(id="otherartistrecommendations",style={'whiteSpace': 'pre-line','display': 'flex'}
)
],
style = {'width': '49%', 'display': 'inline-block'})
],style={"display": "flex"})

Plotly Dash - Bootstrap's cards don't change of color [duplicate]

I'm trying to organize my Plotly Dash dashboard into sections of columns, but I can't understand what I'm doing wrong here. I've included my components in separate dbc.Cols within one dbc.Row and specified the width of the column I'd like for them to take up, but everything is just stacked. Ideally, I'd have the cards in a column all by themselves on the left, then I would have the questions next to them on the right. Can someone please help me diagnose what I'm doing that's causing all my components to stack?
#Import packages
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash()
#App Layout
app.layout = html.Div([
dbc.Row(children=[
dbc.Col(id="card_col",width = 6),
dbc.Col(id="form", width=6, children=[
html.Div([
dbc.FormGroup(children=[
dbc.Label("Question 1"),
dbc.Col(
dcc.Input(type="text", id="q1", placeholder="Enter your info"),
width=6
)
],row=True)
]),
html.Br(),
html.Div(children=[
dbc.FormGroup(children=[
dbc.Label("Question 2?"),
dbc.Col(
dbc.Input(type="text",id="q2",placeholder="Enter your info"),
width=6
)
],row=True)
]),
html.Br(),
html.Div([
dbc.FormGroup(children=[
dbc.Label("Yes/No?"),
dbc.Col(
dbc.RadioItems(id="q3",options=[{"label": "Yes", "value": 1},
{"label": "No", "value": 2}
]
),width=6
)
],row=True)
]),
html.Br(),
html.Div([
html.Button(id='submit-button',
n_clicks=0,
children='Submit Query',
style={'fontSize':24})
])
]) #End of second column
]), #End of row,
dbc.Row(
html.Div([
dcc.Graph(id='graph1')
])
)
])
#app.callback(
Output('card_col','children'),
Input('submit-button','n_clicks'),
State('q1','value'),
State('q2','value'),
State('q3','value'))
def update_cards(n_clicks,input1,input2,input3):
card1 = dbc.Card([
dbc.CardBody([
html.H4(f"{input1}", className="card-title"),
html.P(f"{input1} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
card2 = dbc.Card([
dbc.CardBody([
html.H4(f"{input2}", className="card-title"),
html.P(f"{input2} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
card3 = dbc.Card([
dbc.CardBody([
html.H4(f"{input3}", className="card-title"),
html.P(f"{input3} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
return (card1, card2, card3)
if __name__ == "__main__":
app.run_server()
You haven't included the bootstrap styles:
Linking a stylesheet
dash-bootstrap-components doesn't come with CSS included. This is to give you the freedom to use any Bootstrap v4 stylesheet of your choice. This means however that in order for the components to be styled properly, you must link to a stylesheet yourself.
In Python, each CDN link is available within the dbc.themes submodule and can be used when instantiating the app object.
https://dash-bootstrap-components.opensource.faculty.ai/docs/quickstart/
So instead of this:
app = dash.Dash()
do this:
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

plotly-dash: embed indicator graph inside of a dbc card

I have been banging my head off the wall all day and cannot find a way to fit a dash indicator inside of a dash_bootstrap_components card.
It seems that the body of the card and the graph do not live inside of the card. I am not very familiar with dash so it is difficult to find a way to solve the issue.
here is what I have been able to do so far in terms of plotting the indicator:
fig3 = go.Figure()
fig3.add_trace(go.Indicator(
mode = "number+delta",
number = {"font":{"size":40},'prefix': "$"},
value = 2045672,
delta = {'reference': 30000},
gauge = {'shape': "bullet"},
title = {"text": "On Hand<br><span style='font-size:0.9em;color:gray'></span>"},
#title='Stock On Hand',
domain = {'x': [0, 1], 'y': [0, 1]},
))
fig3.update_layout(paper_bgcolor = "rgba(0,0,0,0)",
plot_bgcolor = "rgba(0,0,0,0)",
autosize=False,
width = 200,
height=200,
)
fig3.update_traces(align="center", selector=dict(type='indicator'))
I am forced to specify width and height for the indicator otherwise it is way too big, however this cause issues because its size does not adjust in regards to the card.
here is the html dash code for the box and the plot:
html.Div(children=[
html.Div(children=[
html.Div(children=[
html.Div(children=[
dbc.Card(
[dbc.CardBody(
[dcc.Graph(figure=fig3)
]
)],className="card", style={"width": "15rem", "height":"8rem"}
),
], className='jumbotron', style={'background-color': '#fffffff'}),
])
],className="col-3 mx-auto"),
],className="row p-0 h-100", style={'background-color': '#f7f7f7', 'height':110}),
], className="full-width p-0 h-100", style={'background-color': '#fffffff'}),
and here is what the final output looks like:
I am not sure what else I can try to bring the graph inside of the box, any help would be appreciated
Remove the instances where you set the height in the style of dash components and the indicator doesn't get cut off.
So you can do something like this:
app.layout = html.Div(
children=[
html.Div(
children=[
html.Div(
children=[
html.Div(
children=[
dbc.Card(
[
dbc.CardBody(
[dcc.Graph(figure=fig3)],
style={"width": "15rem"},
)
]
)
],
className="jumbotron",
style={"backgroundColor": "#fffffff"},
)
],
className="col-3 mx-auto",
)
],
className="row p-0 h-100",
style={"backgroundColor": "#f7f7f7"},
)
],
className="full-width p-0 h-100",
style={"backgroundColor": "#fffffff"},
)
I've also changed the casing of the style properties to camelCase as this is what React (which dash uses) likes.

Align dash core components horizontally

I want to align two Dropdown menus and a DatePickerRange horizontally. But with the following code:
import dash
import dash_core_components as dcc
import dash_html_components as html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
style_dict = dict(width='100%',
border='1.5px black solid',
height='50px',
textAlign='center',
fontSize=25)
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.Dropdown(
id = 'start_hour',
options = [{'label': i, 'value': i} for i in list(range(0,24))],
style=style_dict,
), style={'width': '20%', 'display': 'inline-block'}),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.DatePickerRange(
id='date_picker_range',
style=style_dict
), style={'width': '14%', 'display': 'inline-block', 'fontSize': 20}),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.Dropdown(
id = 'end_hour',
options = [{'label': i, 'value': i} for i in list(range(0,24))],
style=style_dict
), style={'width': '20%', 'display': 'inline-block'}),
])
if __name__ == '__main__':
app.run_server(debug=False, use_reloader=False)
I got this layout:
If I zoom in I got this:
Is it possible to force the components to be aligned at the top edge, no matter how I zoom in or out?
As browser I use Firefox.
I had a problem similar to the one you are describing. I was creating a dashboard that looked like this:
dcc components without proper alignement
As you can see in the image, my dcc components, as well as their titles were not aligned correctly. I tried adding the style parameter verticalAlign and it worked as I expected. This is how the dashboard looked after adding that style parameter:
dcc components aligned
I'm attaching my dashboard Layout code so you can see where I placed the parameter mentioned:
## Dashboard layout
app.layout = html.Div( ## Master div
[
html.Div( ## Dashboard title
[
dcc.Markdown(dash_title)
]
),
html.Div( ## Select menus
[
html.Div( ## Stock select
[
dcc.Markdown(dash_stock_sel),
dcc.Dropdown(
id="select_stock",
options=[{"label": cmp, "value": tickers_base[cmp]["symbol"]} for cmp in tickers_base],
value="TSLA"
)
],
style={
"display": "inline-block",
"width": "20%"
}
),
html.Div( ## Date select dcc components
[
dcc.Markdown(dash_date_sel),
dcc.DatePickerRange(
id="select_dates",
min_date_allowed=date(2015, 1, 1),
max_date_allowed=date.today(),
initial_visible_month=date(2015, 1, 1),
end_date=date.today()
)
],
style={
"display": "inline-block",
"width": "30%",
"margin-left": "20px",
"verticalAlign": "top"
}
),
]
),
html.Div( ## Stock prices graph
[
dcc.Graph(
id="cstock_graph",
figure=stock_graph(def_company, datareader_api, def_start, def_end)
)
]
)
]
)
I hope this answer helps!

Categories

Resources