CSS not working in Shadow DOM when using :host

I created a custom template based on FastListTemplate and add my own ‘app.css’ file. In my app, I want to paint my button blue and the main content heading red. But since both panel components are in a shadow DOM, they are encapsulated by global styles. Hence, I use :host to find the shadow host with the class name and insert styles there.

Expected behavior: Heading should be in red and button should be blue
Actual behavior: Both components have default color from fast.css

Complete, minimal, self-contained example code that reproduces the issue :-

Put both files in the same directory and launch app.py

app.py

import panel as pn
import pathlib
from panel.template import FastListTemplate

class CustomTemplate(FastListTemplate):
    _css = FastListTemplate._css + [pathlib.Path(__file__).parent / "app.css"]

    def __init__(self, **params):
        super().__init__(**params)

app = CustomTemplate()

app.main.append(pn.pane.Markdown("""# Color me red"""))

app.sidebar.append(pn.widgets.Button(name="Color me blue"))

app.servable()

app.css

:host(.solid) .bk-btn {
    background-color: #23B7E5;
    border: 1px solid #19A9D5;
    color: white;
}

:host(.markdown) h1 {
    color: red;
}

Hi @aditya3434

Welcome to the community.

What you are trying to do will not work.

Welcome to the community. With Panel 1.x every component is rendered inside shadow dom to make it work (style) independently of the rest of the app. So you need to get your styles *injected’ into the component using stylesheets like my code below.

import panel as pn

CSS = """
:host(.solid) .bk-btn.bk-btn-default {
    background-color: #23B7E5;
    border: 1px solid #19A9D5;
    color: white;
}

:host(.markdown) h1 {
    color: red;
}
"""

app = pn.template.FastListTemplate()

app.main.append(pn.pane.Markdown("""# Color me red""", stylesheets=[CSS]))

app.sidebar.append(pn.widgets.Button(name="Color me blue", stylesheets=[CSS]))

app.servable()

For more see the Apply CSS guide

Hey Marc. Thanks for the solution! I was just wondering if there was any way to inject global styles from a .css file in a Panel application. Injecting individual styles for each component seems a bit cumbersome.

2 Likes

I agree. I’ve asked for a global way to do this in #4830

1 Like