You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit中Folium地图与背景样式兼容问题修复

解决Streamlit中Folium地图与背景图共存的布局空白问题

问题描述

在Streamlit中同时添加Folium地图和背景图片时,首次运行应用会出现地图下方长白色空白区域;重新运行后空白缩小,但地图仍无法充分利用可用空间。相关代码如下:

import streamlit as st
from streamlit_folium import st_folium
import folium

# setup page
st.set_page_config(page_title="streamlit test", layout="centered")

image_url = "https://img.freepik.com/foto-gratis/fondo-gris-pintado_53876-94041.jpg"

# CSS image
st.markdown(f"""
    <style>
        .stApp {{
            background-image: url("{image_url}");
            background-size: cover;
            background-position: center;
            background-color: transparent;
            font-family: 'Pacifico', cursive;
            color: #ffb6c1;
        }}
    </style>
""", unsafe_allow_html=True)

# Show Map
st_folium(
    folium.Map(
        location=[-20, 130], 
        zoom_start=5, 
        control_scale=True), 
    width=600, 
    height=400)

解决方案

空白问题主要来自Streamlit默认组件容器的额外边距、背景图的滚动显示问题,以及固定尺寸的地图无法适配布局。以下是修复后的代码:

import streamlit as st
from streamlit_folium import st_folium
import folium

# 可选:设置为wide布局让内容更充分利用空间,也可保留centered
st.set_page_config(page_title="streamlit test", layout="wide")

image_url = "https://img.freepik.com/foto-gratis/fondo-gris-pintado_53876-94041.jpg"

# 自定义CSS修复布局空白与背景显示
st.markdown(f"""
    <style>
        .stApp {{
            background-image: url("{image_url}");
            background-size: cover;
            background-position: center;
            background-attachment: fixed; /* 固定背景图,避免滚动空白 */
            background-color: transparent;
            font-family: 'Pacifico', cursive;
            color: #ffb6c1;
        }}
        /* 移除st_folium外层容器的额外边距内边距 */
        .st-emotion-cache-12w0qpk {{
            padding: 0 !important;
            margin: 0 !important;
        }}
        /* 确保地图容器无额外边框和高度限制 */
        .folium-map {{
            border: none !important;
            height: 100% !important;
        }}
        /* 移除页面底部默认内边距 */
        .st-emotion-cache-16txtl3 {{
            padding-bottom: 0 !important;
        }}
    </style>
""", unsafe_allow_html=True)

# 用容器包裹地图,配合自适应宽度让布局更灵活
with st.container():
    st_folium(
        folium.Map(
            location=[-20, 130], 
            zoom_start=5, 
            control_scale=True), 
        use_container_width=True,  # 自适应容器宽度
        height=600  # 根据需求调整地图高度
    )

关键修复点

  • 添加background-attachment: fixed:让背景图固定在视口,避免滚动时出现空白区域
  • 覆盖默认组件样式:移除st_folium外层容器和页面底部的额外padding/margin,消除不必要的空白
  • 使用use_container_width=True:替代固定宽度,让地图自适应容器空间,提升布局适配性
  • 用st.container()包裹地图:增强布局的可控性,避免组件间的干扰

内容的提问来源于stack exchange,提问作者PeCaDe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:55:10