A JavaScript-free custom element implementation
- Published at
- Updated at
- Reading time
- 1min
Some people love custom elements, and it seems that even more people are entirely against them. And while I'm leaning towards using them, today I learned a fascinating custom elements take.
I've been reading one of Adam Argyle's excellent component walk-throughs, and Adam shared a tool-tip
custom element that works without the usual customElements
JavaScript instruction.
To quote Adam:
You could think of a custom element like a classname with less specificity.
That's an interesting take because it changes the mental model around custom elements! Custom elements are usually used to encapsulate functionality as web components with JavaScript, but one could also use them as another style hook with lower specificity than class selectors. Neat!
Use Polypane's specificity calculator if you want to learn more about CSS specificity.
And to make the custom element accessible, Adam's example tool-tip
component receives its semantic meaning via ARIA...
<tool-tip role="tooltip">A tooltip</tool-tip>
... and the show/hide functionality is then added via CSS has()
. 😲
/* Only show the custom element when its parent is hovered, focused, or activated */
:has(> tool-tip):is(:hover, :focus-visible, :active) > tool-tip {
opacity: 1;
transition-delay: 200ms;
}
Very smart!
Join 5.5k readers and learn something new every week with Web Weekly.