Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Last active August 20, 2023 15:52
Show Gist options
  • Save elfsternberg/46a5cd4f540182c2aba9efe479f13be6 to your computer and use it in GitHub Desktop.
Save elfsternberg/46a5cd4f540182c2aba9efe479f13be6 to your computer and use it in GitHub Desktop.
Important Shadow Context Demo
<odd-bird>Miriam Suzanne</odd-bird>
<template id="odd-bird">
<style>
/* these styles come from the shadow context */
span {
color: rebeccapurple;
font-family: fantasy !important;
font-size: 3em;
font-weight: bold !important;
}
</style>
<span part="name">
<slot>Odd McBirdle</slot>
</span> is Odd…
</template>
// copypasta from https://twitter.com/WestbrookJ/status/1369350640019922948
//
// changed by Elf: The `attachShadow` was a series of poorly named variable steps,
// the last of which was an abstraction leak (no other code used it). Choices
// were (1) fix the names, (2) just inline the whole thing. I went with the
// latter; arguably rude and unclear, but in the context of a styling-only tag
// could be considered idiomatic.
customElements.define(
"odd-bird",
class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"})
.appendChild(document.getElementById("odd-bird").content);
);
}
}
);
::part(name) {
/* page styles win by default */
color: mediumvioletred;
/* shadow-DOM styles win when important */
/* font-family: monospace !important; */
}
/* page layout */
html {
height: 100%;
}
body {
display: grid;
min-height: 100%;
place-content: center;
padding: 1em;
}
@elfsternberg
Copy link
Author

There is an important lesson in this code about the low-level primitives that are used by Lit-Element, and how they behave. I don't think I exploit this enough when writing my own Lit-Element code, and I want to keep it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment