Page elements shift downward with every st.markdown() call in Streamlit - How to prevent layout movement?

Environment:

  • Python 3.12.0
  • Streamlit 1.45.1
  • Windows 11

Problem Description:
In my Streamlit application, every call to st.markdown() causes all page elements to shift downward. This creates accumulating white space and misaligned layouts, especially noticeable when applying custom CSS styles.

import streamlit as st

Each call to this function pushes content down

main.py:


pages = {
   "examples1": [
        st.Page("pages/example1111.py")
    ]
}
def apply_css():
    css = """
    <style>
    .stHeading {
        display: flex;
        justify-content: center;
        width: 100%;
    }
    .stSelectbox > div > div {
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    .stSelectbox > div > div:hover {
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    </style>
    """
    st.markdown(css, unsafe_allow_html=True)

apply_css() 
pg = st.navigation(pages,expanded=False)
pg.run()

in other pages will creates accumulating white space just like the image.

you can avoid that if you use st.html for injecting CSS instead:

import streamlit as st

css = """
.st-key-pink-box {
    background: linear-gradient(90deg, hotpink, purple);
    color: white;
}
"""
css = f"<style>{css}</style>"

if st.toggle("Use `st.markdown`"):
    st.markdown(css, unsafe_allow_html=True)
    st.divider()
    st.header("❌ My app injecting CSS with `st.markdown`")
else:
    st.html(css)
    st.divider()
    st.header("✅ My app injecting CSS with `st.html`")

with st.container(key="pink-box"):
    "Some text " * 50
2 Likes

Thanks for the clear solution ! it’s work perfect!