feat(docs): add guide for shadow dom & constructable stylesheets

This commit is contained in:
Ayo Ayco 2025-03-30 12:14:56 +02:00
parent 822c4d3984
commit ea4cca1958
3 changed files with 59 additions and 9 deletions

View file

@ -10,7 +10,19 @@ Try it now [on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?
Example:
```js
class ShadowElement extends WebComponent {
static shadowRootInit = {
mode: "closed",
};
mode: 'open', // can be 'open' or 'closed'
}
get template() {
return html`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('shadow-element', ShadowElement)
```

View file

@ -3,6 +3,15 @@ title: Styling
slug: styling
---
There are two ways we can safely have scoped styles:
1. Using style objects
2. Using the Shadow DOM and constructable stylesheets
It is highly recommended to use the second approach, as with it, browsers can assist more for performance.
## Using style objects
When using the built-in `html` function for tagged templates, a style object of type `Partial<CSSStyleDeclaration>` can be passed to any element's `style` attribute. This allows for calculated and conditional styles. Read more on style objects [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration).
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
@ -10,7 +19,7 @@ Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-sty
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class StyledElements extends WebComponent {
class StyledElement extends WebComponent {
static props = {
emphasize: false,
type: 'warn',
@ -41,5 +50,39 @@ class StyledElements extends WebComponent {
}
}
customElements.define('styled-elements', StyledElements)
customElements.define('styled-elements', StyledElement)
```
## Using the Shadow DOM and Constructable Stylesheets
If you [use the Shadow DOM](/shadow-dom), you can add a `static styles` property of type string which will be added in the `shadowRoot`'s [`adoptedStylesheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/adoptedStyleSheets).
```js
class StyledElement extends WebComponent {
static shadowRootInit = {
mode: 'open',
}
static styles = `
div {
background-color: yellow;
border: 1px solid black;
padding: 1em;
p {
text-decoration: underline;
}
}
`
get template() {
return html`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElement)
```

View file

@ -2,11 +2,6 @@
import { WebComponent, html } from '../../src/index.js'
class StyledElements extends WebComponent {
static props = {
condition: false,
type: 'info',
}
static shadowRootInit = {
mode: 'open',
}