CSS of st.markdown

Summary

Hi, I would like to make the code of st.code to have the same CSS as st.markdown, same font, size, etc. The CSS has to go inside code {}.

Steps to reproduce

Code snippet:

        with stylable_container(
                "codeblock",
                """
                code {
                    white-space: pre-wrap !important;
                }
                """
        ):
            st.code(message, language=None, line_numbers=False)
1 Like

Hi @Erica! :wave:

It’s not currently possible to change the font format in st.code() to mimic the font formatting you would find in e.g. st.markdown.

You may be able to hack it via CSS - by checking the CSS styles applied to the st.markdown component and then apply those styles to the st.code component.

However, this isn’t something I’ve tried, so you would have to experiment :slight_smile:

Happy Streamlit-ing! :balloon:
Charly

Hi @Charly_Wargnier, thanks for the reply. I have already tried that, for example to modify the font. Sadly it did not change anything.

Maybe @blackary has a trick? :wink:

Create a custom css variable and specify the css properties, use st.markdown to put the custom css into the streamlit app, then use st.code inside a st.markdown. Did you try this?

1 Like

This updates the font size and font-family

import streamlit as st
from streamlit_extras.stylable_container import stylable_container

message = """
import streamlit as st

st.write("hi")
"""

with stylable_container(
    "codeblock",
    """
                code {
                    white-space: pre-wrap !important;
                    font-family: "Source Sans Pro", sans-serif !important;
                    font-size: 1rem !important;
                }
                """,
):
    st.code(message, language=None, line_numbers=False)

st.markdown(message)

You can use the browser inspector to see what the css values are for st.markdown, and copy those as-needed.

@blackary thank you very much, this is perfect :innocent:.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.

Great solution! Thanks, @blackary! :raised_hands: