Stylesheet

The stylesheet class property is the primary way to define styling for your component. WebComponent accepts a variety of stylesheet formats and processes them automatically based on your Shadow DOM configurations.

Supported Stylesheet Formats

You can assign a CSS string, a native CSSStyleSheet instance, or a CSS import assertion to the stylesheet property.

1. CSS Strings

The simplest way is to define your stylesheet as a plain CSS string:

javascript
1import { WebComponent, html } from '@beforesemicolon/web-component'2 3class SimpleBtn extends WebComponent {4    stylesheet = `5        button {6            background-color: var(--button-bg, ButtonFace);7            color: var(--button-color, ButtonText);8            border: 1px solid var(--button-border, ButtonText);9            padding: 8px 16px;10            border-radius: 4px;11            cursor: pointer;12        }13        button:hover {14            opacity: 0.9;15        }16    `17 18    render() {19        return html`<button><slot></slot></button>`20    }21}

2. CSS Import Assertions

If your build environment or browser supports CSS module imports, you can import a .css file directly and assign the stylesheet export:

javascript
1import { WebComponent, html } from '@beforesemicolon/web-component'2import styleSheet from './style.css' with { type: 'css' }3 4class AssetBtn extends WebComponent {5    stylesheet = styleSheet6 7    render() {8        return html`<button><slot></slot></button>`9    }10}

3. Native CSSStyleSheet

You can also construct stylesheets imperatively:

javascript
1const sheet = new CSSStyleSheet()2sheet.replaceSync('button { font-weight: bold; }')3 4class BoldBtn extends WebComponent {5    stylesheet = sheet6}

Shadow DOM vs. Light DOM Behavior

Behind the scenes, WebComponent uses Adopted StyleSheets to inject your styles. Where those stylesheets are adopted depends on your component configuration.

Under Shadow DOM (Default)

If Shadow DOM is active, the style is adopted by the Shadow Root of the component. It keeps styles isolated and allows the use of the :host selector.

css
1:host {2    display: inline-block;3}

Under Light DOM

If you disable Shadow DOM by setting config.shadow = false, the component cannot adopt styles locally since there is no Shadow Root. WebComponent handles this by adopting the styles on the document (or the closest containing ancestor shadow root).

Because global styles can leak, WebComponent automatically parses and rewrites specific selectors:

css
1/* Original CSS */2:host {3    display: block;4}5:host(.active) {6    color: red;7}8:host-context(.dark-theme) {9    background-color: black;10}11 12/* Rewritten for <my-element> */13my-element {14    display: block;15}16my-element.active {17    color: red;18}19.dark-theme my-element {20    background-color: black;21}

This ensures your styling rules continue to work as expected, even if you decide to toggle the Shadow DOM configuration.

edit this doc