Python Dash 侧边栏DIV添加滚动条及fixed定位冲突问题咨询
解决方案
你当前使用position: fixed固定侧边栏的布局逻辑是正确的,不需要调整,只需要给侧边栏添加溢出滚动属性即可实现需求。
具体修改步骤
- 在
SIDEBAR_STYLE样式字典中添加一行"overflow-y": "auto",该属性的作用是当侧边栏内的内容高度超过侧边栏容器可视高度时,自动显示纵向滚动条,内容未溢出时则隐藏滚动条,不占用额外布局空间。
修改后的SIDEBAR_STYLE参考:
SIDEBAR_STYLE = { "position": "fixed", "top": 0, "left": 0, "bottom": 0, "width": "16rem", "padding": "2rem 1rem", "background-color": "#f8f9fa", "overflow-y": "auto" # 新增的滚动配置 }
完整可运行代码
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) # 新增了overflow-y配置的侧边栏样式 SIDEBAR_STYLE = { "position": "fixed", "top": 0, "left": 0, "bottom": 0, "width": "16rem", "padding": "2rem 1rem", "background-color": "#f8f9fa", "overflow-y": "auto" } # 主内容区样式无需修改 CONTENT_STYLE = { "margin-left": "18rem", "margin-right": "2rem", "padding": "2rem 1rem", "display": "inline-block" } sidebar = html.Div( [ html.H2("Sidebar", className="display-4"), html.Hr(), html.P( "A simple sidebar", className="lead" ), # 可自行调整数量测试滚动效果 *[html.P(f"测试内容行{i}") for i in range(100)] ], style=SIDEBAR_STYLE, ) maindiv = html.Div( id="first-div", children=[ # first row html.Div([ html.H2("First Row"), html.Hr(), html.P( "First row stuff", className="lead" ) ]), # second row html.Div([ html.H2("Second Row"), html.Hr(), html.P( "Second row stuff", className="lead" ) ]) ], style=CONTENT_STYLE ) app.layout = html.Div([sidebar, maindiv]) if __name__ == "__main__": app.run_server(port=8888)
内容的提问来源于stack exchange,提问作者atrusty
相关产品推荐
相关产品推荐

