Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created September 3, 2024 17:54
Show Gist options
  • Save tomhodgins/2cfdd725cf3f0aa7c07753d492a6c592 to your computer and use it in GitHub Desktop.
Save tomhodgins/2cfdd725cf3f0aa7c07753d492a6c592 to your computer and use it in GitHub Desktop.
<!doctype html>
<title>CSS Shadow Root styling</title>
<script type=module>
class CustomElement extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'closed'})
shadow.innerHTML = `
<style>
:host {
--background: yellow;
}
:host div {
background: var(--background);
}
</style>
<div>Shadow Root Content</div>
`
}
}
customElements.define('custom-element', CustomElement)
</script>
<!-- With Default styling -->
<custom-element></custom-element>
<!-- With style override from DOM -->
<custom-element style="--background: lime;"></custom-element>
<!-- With style override from CSS Stylesheet -->
<custom-element id=css></custom-element>
<style>
#css {
--background: hotpink;
}
</style>
<!-- With style override from JavaScript -->
<custom-element id=js></custom-element>
<script type=module>
document.querySelector('#js').style.setProperty('--background', 'orange')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment