Global CSS stylesheet for NiceGUI

1.2k Views Asked by At

Is there a way to provide a global CSS stylesheet?

I want to override underlying elements or configure all elements at once by my own css classes.

I know this style (ui.label('label ').style('color: rgb(..) syntax, but such configuration has to be repeated for every element.

2

There are 2 best solutions below

5
Shreyesh Desai On

You can style the whole HTML body by using the ui.query to provide a global CSS stylesheet.

ui.query('body').style('background-color: red')
ui.run()

You can find more about it on official documentation here.


Update 1:

If the CSS doesnt need to be assigned to the whole body, but selective elements only, we can append the elements to a common list while creating and assign the style together later on.

from typing import List
from nicegui import ui
from nicegui.elements.label import Label   # importing for type comparison
from nicegui.elements.label import Button  # importing for type comparison

css_elements:List = []

label1 = ui.label('My Label 1')
css_elements.append(label1)
button1 = ui.button('My Button 1')
css_elements.append(button1)

# styling all elements together in a for loop
for element in css_elements:
    element.style('background-color: red')
   
    # We can also style based upon type of element
    if isinstance(element, Label):
        element.style('background-color: blue')
    elif isinstance(element, Button):
        element.style('background-color: green')
    else:
        element.style('background-color: red')

ui.run()

Update 2:

As per niceGUI's creator's response here, to provide custom CSS, you can just add it as Head html using ui.add_head_html method.

ui.add_head_html('''
<style>
.colored-radio div:nth-of-type(1) > .q-radio > .q-radio__inner--truthy {
  color: red !important;
}
.colored-radio div:nth-of-type(2) > .q-radio > .q-radio__inner--truthy {
    color: green !important;
}
.colored-radio div:nth-of-type(3) > .q-radio > .q-radio__inner--truthy {
    color: blue !important;
}
</style>
''')

ui.radio(['red', 'green', 'blue']).classes('colored-radio')

OR

You can reference using a CSS file as well.

app.add_static_files('styles.css', 'styles.css')
ui.add_head_html('''<link rel="stylesheet" type="text/css" href="styles.css">''')
0
rolo On

This answer above and from Github lead me to 2 solutions:

My favourite:

# style-sheet file is: Path(__file__).parent / "static" / "styles.css"
# the root folder or single file was not working
app.add_static_files('/static', 'static')
ui.add_head_html('<link rel="stylesheet" type="text/css" href="/static/styles.css">')

or:

ui.add_head_html("<style>" + open(Path(__file__).parent / "static" / "styles.css").read() + "</style>")