https://github.com/nonsalant/colocated-styles
Pattern for co-locating CSS in web components
https://github.com/nonsalant/colocated-styles
css css-modules patterns web-components
Last synced: 5 months ago
JSON representation
Pattern for co-locating CSS in web components
- Host: GitHub
- URL: https://github.com/nonsalant/colocated-styles
- Owner: nonsalant
- Created: 2025-08-12T21:41:05.000Z (5 months ago)
- Default Branch: main
- Last Pushed: 2025-08-13T19:59:36.000Z (5 months ago)
- Last Synced: 2025-08-13T21:31:38.024Z (5 months ago)
- Topics: css, css-modules, patterns, web-components
- Language: JavaScript
- Homepage: https://colocated-styles.netlify.app/
- Size: 6.84 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.MD
Awesome Lists containing this project
README
# Co-located Styles
A pattern I'm using to co-locate styles in web components until [CSS Modules](https://frontendmasters.com/blog/architecture-through-component-colocation/) become more widely supported.
The `cssPaths` static property is an array that contains the paths to the stylesheets that should be loaded when the component is instantiated. The paths are relative to the component's JavaScript file and are only loaded once regardless of how many instances of the component are created.
The `addAssets` method is responsible for loading these stylesheets and adding them to the component's *asset host*.
```js
this.assetHost = this.shadowRoot ?? this.getRootNode();
```
The `assetHost` property is the shadow root of the component if it has one, or the document itself if the component is not in a shadow DOM. If the component is inside the shadow DOM of another component, the `assetHost` will be the closest ancestor shadow root.
## Live Demo
[colocated-styles.netlify.app](https://colocated-styles.netlify.app/)