LoginSignup
7
6

More than 3 years have passed since last update.

Python DashのCSS拡張とBootStrap導入

Posted at

Python DashのCSS拡張とBootStrap導入

WebサービスとしてPython Dashを使う場合、そのままだとUI・デザインの拡張性が弱いため
Python DashのCSS拡張とBootStrap導入をまとめた

Python Dashの導入方法は以下の記事を参考

CSS拡張

Python DashでCSSを使う場合には大きく2パターン

dash_html_components style指定

styleをDict追加することが可能
ドキュメントなどはこちらが使われていることが多い

import dash_html_components as html

app.layout = dbc.Container(
    [
        html.H1("BootStrap Sample", style={"font-size": 100, "color": "red"}),
        html.Hr(),
    ],
)

assets以下にcssを配置

mediaなど対応する場合には独自cssを使うしかない
assets以下にcssを配置すると独自cssが利用可能
custom.css

h1 {
    font-size: 100px; 
    color: "red";
}

結果
スクリーンショット 2021-03-28 14.14.34.png

BootStrap導入

dash-bootstrap-components

公式サイト

GitHub

インストール

$ pip install dash-bootstrap-components

導入

import dash
import dash_bootstrap_components as dbc


app = dash.Dash(
    __name__,
    suppress_callback_exceptions=True,
    external_stylesheets=[dbc.themes.BOOTSTRAP],
    meta_tags=[
        {"name": "viewport", "content": "width=device-width, initial-scale=1"}
    ],
)

グリッド

Python Dash内でBootStrapが利用可能
グリッドの記述方法は以下

import plotly.express as px


df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length")

app.layout = dbc.Container(
    [
        html.H1("BootStrap Sample"),
        html.Hr(),
        dbc.Row(
            [
                dbc.Col(dcc.Graph(figure=fig), md=4),
                dbc.Col(dcc.Graph(figure=fig), md=8),
            ],
            align="center",
        ),
    ],
    fluid=True,
)

例:HTML出力
BootStrapのグリッドが利用されていた

<div class="container-fluid">
    <h1>BootStrap Sample</h1>
    <hr>
    <div class="align-items-center row">
        <div class="col-md-4">
            <div class="dash-graph">...</div>
        </div>
        <div class="col-md-8">
            <div class="dash-graph">...</div>
        </div>
    </div>
</div>

結果

BootStrapグリッドが利用されレスポンシブ対応が行われた
dash-bootstrap-componentsを使うことで使い慣れたBootStrapコンポーネントが利用可能はありがたい

他のBootStrapコンポーネントも大体利用可能

PC
スクリーンショット 2021-03-28 14.19.44.png

スマホ
screencapture-localhost-8080-page-1-2021-03-28-14_19_58.png


いいね!と思ったら LGTM お願いします :clap::clap::clap:

【PR】プログラミング新聞リリースしました! → https://pronichi.com
【PR】週末ハッカソンというイベントやってます! → https://weekend-hackathon.toyscreation.jp/about/

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6