2.5. Custom HTML#

Adding custom HTML in Streamlit allows you to develop more customized applications that fit your need. While it is not always necessary, it is useful to understand how to embed HTML within an application.

Custom HTML can be added via st.markdown(). In order for your HTML to appear on the page, however, you must pass a keyword argument unsafe_allow_html=True. This allows the HTML to be rendered. Let’s look at a basic example where we want to display text with a background color of yellow. We can do this by wrapping our text in an a tag in HTML and setting the style’s background color to yellow.

html = """
<a style='background:yellow'>This text has a yellow background</a>
"""
st.header("Without unsafe_allow_html=True")
st.markdown(html)

If we do not set unsafe_allow_html to True, then our result will look like this:

../_images/custom_html1.png

Fig. 2.15 Example of Custom HTML in Streamlit when Blocked#

If we do set it to True, then our result will look like this:

../_images/custom_html2.png

Fig. 2.16 Example of Custom HTML in Streamlit when Allowed#

While this lets you design more robust apps, it does introduce certain security issues.