CSS-Only Custom Elements
There's a quiet trend picking up steam in the web components world: developers using custom-element-shaped markup that never calls customElements.define() . No class, no lifecycle callbacks, no component JavaScript at all. Just a tag name and a stylesheet. At first glance, this feels like it's missing the point of custom elements. However, an undefined custom-element name is still valid HTML…
A growing trend in the web components landscape involves developers utilizing custom-element-shaped markup without ever invoking customElements.define(). This approach eliminates the need for a class, lifecycle callbacks, or any JavaScript code, relying solely on a tag name and a stylesheet. At first glance, this may seem contrary to the purpose of custom elements, but an undefined custom-element name is still valid HTML markup that browsers can easily select, style, and compose using only CSS. For certain UI patterns, this CSS-only method suffices.
The primary benefits of the CSS-only method include minimal JavaScript cost, no component bundle, and no need for custom-element upgrade work. The browser treats the element as an ordinary undefined element, albeit with potential impacts on rendering due to CSS selector matching and layout complexity. Progressive enhancement remains intact, as a failed CSS load does not break functionality, and semantic children (such as headings and links) retain their inherent meaning.
Furthermore, the CSS-only method promotes meaningful tag names as an API, making the design system's vocabulary visible directly in the DOM. This enhances visibility in developer tools, view-source, and designer handoff notes. Custom CSS properties can serve as the public API, allowing consumers to customize components without altering the markup. Attribute selectors handle state and variants, while slot-like attributes facilitate composition, all without JavaScript.
To build a badge component using this CSS-only technique, you would define CSS variables for spacing, colors, and other properties. These variables are then referenced in various rules, allowing for easy customization. For example, a "danger" variant can be achieved by simply adding the "variant= danger" attribute to the tag. The component's markup consists of the tag name, attributes, and SVG icons, all styled using CSS.
When styling, it's essential to explicitly set the display mode, as undefined custom elements default to inline layout. Additionally, aria-hidden="true" should be used for purely decorative icons to prevent them from being announced by assistive technology. By following these guidelines and leveraging the CSS-only custom elements approach, developers can create efficient, maintainable, and accessible UI components.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.