Skip to content

Instantly share code, notes, and snippets.

@heyMP
Created October 25, 2021 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyMP/bc54b584816ae05495cbe95d00874976 to your computer and use it in GitHub Desktop.
Save heyMP/bc54b584816ae05495cbe95d00874976 to your computer and use it in GitHub Desktop.
Declarative Adopted Stylesheets
<my-element>
<template slot="styles">
<style>
/* CSS tweaks escape hatch */
* {
color: pink;
}
</style>
</template>
</my-element>
import { adoptStyles, css, html, LitElement, unsafeCSS } from 'lit';
class MyElement extends LitElement {
getAdoptedStyles() {
const stylesTemplate = this.shadowRoot
.querySelector('slot[name=styles]')
.assignedNodes()[0];
if (stylesTemplate) {
try {
const styles =
stylesTemplate.content.querySelector('style').textContent;
adoptStyles(this.shadowRoot, [
...this.constructor.styles,
css`
${unsafeCSS(styles)}
`,
]);
} catch (e) {
console.error(e.message);
}
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment