Colored boxes around sections of a sentence

Hello,
I am trying to put two different coloured box around two different text in the same line. I know that currently a dedicated feature is not available. But as is visible in the twitter link you have attached https://twitter.com/_inesmontani/status/1179155259819806721 in one of the discussions, she has somehow managed to do this. So could anyone please tell me how see was able to do that. I went through her git code but couldn’t figure out how:").
image

This is what I tried:
HTML_l = div style=“ovrflow-x:auto;color:white;border: 1px solid #e6e9ef; border-radius: 0.4rem;
padding: 0.5rem; background-color:#377ed4 ;margin-bottom: 1rem; width: 250px;font-weight:500 ;float:left”>Total: {} /div

HTML_r = div style=“ovrflow-x:auto;color:white;border: 1px solid #e6e9ef; border-radius: 0.4rem;
padding: 0.5rem; background-color:#377ed4 ;margin-bottom: 1rem; width: 250px;font-weight:500 ;float:right”>Total: {} /div

t.write((HTML_l.format(‘text1’),HTML_r.format(‘text2’)),unsafe_allow_html=True)
But didn’t work out? Could someone please help:)

1 Like

Hi @rutvik,

I usually put my CSS in an external file and then load it into Streamlit, then the rest is pure HTML/CSS + python f-string formatting…

  • style.css
.highlight {
  border-radius: 0.4rem;
  color: white;
  padding: 0.5rem;
  margin-bottom: 1rem;
}
.bold {
  padding-left: 1rem;
  font-weight: 700;
}
.blue {
  background-color: lightcoral;
}
.red {
  background-color: lightblue;
}
  • load_css.py
"""
https://discuss.streamlit.io/t/are-you-using-html-in-markdown-tell-us-why/96/25
"""
import streamlit as st

def local_css(file_name):
    with open(file_name) as f:
        st.markdown('<style>{}</style>'.format(f.read()), unsafe_allow_html=True)
  • app.py
import streamlit as st

from load_css import local_css

local_css("style.css")
 
t = "<div>Hello there my <span class='highlight blue'>name <span class='bold'>yo</span> </span> is <span class='highlight red'>Fanilo <span class='bold'>Name</span></span></div>"

st.markdown(t, unsafe_allow_html=True)

image

6 Likes

Great solution by @andfanilo. You might also want to check out the new spacy-streamlit building blocks by SpaCy folks.

1 Like