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.define 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.

Calculated specificity for 'tooltip' (0,0,1) and '.tool-tip' (0,1,0)

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!

Was this post helpful?
Yes? Cool! You might want to check out Web Weekly for more WebDev shenanigans. The last edition went out 19 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles