Created
October 25, 2021 20:56
-
-
Save heyMP/bc54b584816ae05495cbe95d00874976 to your computer and use it in GitHub Desktop.
Declarative Adopted Stylesheets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<my-element> | |
<template slot="styles"> | |
<style> | |
/* CSS tweaks escape hatch */ | |
* { | |
color: pink; | |
} | |
</style> | |
</template> | |
</my-element> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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