Custom Elements as Semantic Markers
Custom elements can be used to add semantic meaning to your HTML structure even without JavaScript. This approach replaces "div soup" with meaningful, descriptive element names.
โ Old Way: Div Soup
โ New Way: Semantic Custom Elements
Demo 1: Product Grid Component
A responsive grid displaying product cards with semantic custom elements. Notice how the element names clearly describe what they represent.
Custom Elements Used
<product-grid>- Container for product cards<product-card>- Individual product wrapper<card-image>- Product image container<card-content>- Content wrapper<product-title>- Product name<product-description>- Product details<price-display>- Price information<product-rating>- Star rating display<card-actions>- Action buttons container
HTML Structure
Live Demo
CSS Styling
Demo 2: User Profile Component
Display component showing user information with profile stats. Demonstrates how custom elements can create a clear information hierarchy.
Custom Elements Used
<user-profile>- Profile container<profile-avatar>- User image<profile-info>- User information wrapper<user-name>- Display name<user-role>- Job title/role<user-email>- Email address<profile-stats>- Statistics container<stat-item>- Individual stat
HTML Structure
Live Demo
CSS Architecture Tips
To use custom elements well consider adopting modern CSS features including:
- Tokens (CSS variables) for consistent spacing, colors, and typography
- CSS Layers for organized cascade control
- CSS Nesting for encapsulation
- Relative values for fluidity
- Container queries for responsive behavior
Self-Contained Demo Styles
shared.css import. These pages keep each demo file fully self-contained instead โ literal values, no imports โ so any single demo can be copied out on its own and still work.CSS Layers
Layers control cascade specificity:
Key Takeaways
โญ Important Principles
- Progressive Enhancement: HTML structure works without JavaScript
- Semantic Naming: Element names describe their purpose
- Accessibility First: Proper ARIA labels and keyboard navigation
- Modern CSS: Utilize layers and nesting for organized cascade control and simplicity
- Design Tokens: Consistent spacing, colors, and typography
Don't Abuse Custom Elements
Use standard HTML elements when they exist:
- โ
Use
<header>,<footer>,<nav>,button, etc. - โ Don't create
<section-header>or<section-footer>ormy-button
Next Steps
In Step 2: Custom elements, we'll add JavaScript to enhance these elements:
- Register elements with
customElements.define() - Create proper classes extending
HTMLElement - Split setup between the constructor and
connectedCallback - See what "upgrade" means when the definition arrives after the markup
- Compare autonomous elements with customized built-ins