🎨 Web Component with External CSS

Example: ProductCard Component with Linked CSS File

💡 Key Concept: External CSS in Shadow DOM

Unlike the other components (UserCard, CounterComponent) that use inline CSS with <style> tags inside the component, this ProductCard component demonstrates how to link an external CSS file in Shadow DOM.

Product Catalog Demo

Click "Add to Cart" or "Details" buttons to see custom events in action.

Event Log

No events yet. Interact with the products above.

How to Use External CSS in Shadow DOM

1. Create the CSS File

/* src/styles/product-card.css */
:host {
  display: block;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.product-card {
  background: var(--color-background, white);
  border-radius: 0;
  /* ... more styles ... */
}

2. Link CSS in Component's Shadow DOM

// src/components/ProductCard.js
class ProductCard extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }
  
  render() {
    this.shadowRoot.innerHTML = `
      <link rel="stylesheet" href="/src/styles/product-card.css">
      
      <div class="product-card">
        <!-- Component HTML -->
      </div>
    `;
  }
}

3. Import and Use the Component

// In your main.js or HTML
import './components/ProductCard.js';

// In your HTML
<product-card
  name="Product Name"
  price="99.99"
  description="Description here"
  rating="4.5"
  stock="10"
  category="Category">
</product-card>

Comparison: Inline CSS vs External CSS

Inline CSS (Most Components)

render() {
  this.shadowRoot.innerHTML = `
    <style>
      .card { 
        background: white;
        /* All CSS here */
      }
    </style>
    <div class="card">...</div>
  `;
}

External CSS (ProductCard)

render() {
  this.shadowRoot.innerHTML = `
    <link rel="stylesheet" href="/src/styles/product-card.css">
    <div class="card">...</div>
  `;
}

Documentation

Next Step