I want to change the fontsize of the label above an input widget in my streamlit app.
What I have so far:
import streamlit as st
label = "Enter text here"
st.text_input(label)
I want to make the label "Enter text here" bigger.
I know there are various ways to change fontsize in st.write()
. So, I tried some of them:
st.write(f"# {label}") # <--- works
st.text_input(f"# {label}") # <--- doesn't work
s = f"<p style='font-size:20px;'>{label}</p>"
st.markdown(s, unsafe_allow_html=True) # <--- works
st.text_input(s) # <--- doesn't work
but as commented above, neither work. How do I make it work?
So did a little digging and it turns out that streamlit has a components API which can be used to render an html string. So we can basically use a little javascript to change the font size of a specific label. Since labels are unique for each widget, we can simply search for the paragraph element whose inner text that matches the label.
A working example:
label = "Enter text here"
st.text_input(label)
st.components.v1.html(
f"""
<script>
var elems = window.parent.document.querySelectorAll('div[class*="stTextInput"] p');
var elem = Array.from(elems).find(x => x.innerText == '{label}');
elem.style.fontSize = '20px'; // the fontsize you want to set it to
</script>
"""
)
It renders a field that looks like the following:
A convenience function that can be used to change font size, color and font family (you can actually add more as you wish):
def change_label_style(label, font_size='12px', font_color='black', font_family='sans-serif'):
html = f"""
<script>
var elems = window.parent.document.querySelectorAll('p');
var elem = Array.from(elems).find(x => x.innerText == '{label}');
elem.style.fontSize = '{font_size}';
elem.style.color = '{font_color}';
elem.style.fontFamily = '{font_family}';
</script>
"""
st.components.v1.html(html)
label = "My text here"
st.text_input(label)
change_label_style(label, '20px')
It turns out you can use LaTeX expressions, so I ended up using latex text in math mode because you can change font size using \Huge
, \LARGE
etc. in Latex. Since the default font in streamlit is sans-serif, I used \textsf{}
. A working example:
import streamlit as st
st.text_input(r"$\textsf{\Large Enter text here}$")
which renders
The above uses \Large
font size. The following is an example using all possible font size options:
label = r'''
$\textsf{
\Huge Text \huge Text \LARGE Text \Large Text
\large Text \normalsize Text \small Text
\footnotesize Text \scriptsize Text \tiny Text
}$
'''
st.text_input(label)