GitHub v1.3.1
Lesson 07

Theming with Variables

Build components that are infinitely customizable by consumers using CSS Custom Properties and Coralite's reactive style export.

Exposing Theme Tokens

Instead of hardcoding colors directly into your component's CSS, you should expose them as CSS custom properties (variables) with sensible fallbacks. This allows consumers to theme your component without rewriting your CSS.

css
Code copied!
  :host {
    /* Expose variables with fallbacks */
    --card-bg: var(--bg-card, #111827);
    --card-text: var(--text-primary, #F8FAFC);
    --card-border: var(--border-subtle, #1F2937);
  }
  
  .card {
    background: var(--card-bg);
    color: var(--card-text);
    border: 1px solid var(--card-border);
    padding: 24px;
    border-radius: 8px;
  }

Overriding from the Parent

Consumers can now override these variables directly on the host element, or from any parent container, using standard CSS.

html
Code copied!
  <!-- Override the variables inline -->
  <my-card style="--card-bg: #8B5CF6; --card-text: #FFFFFF;">
    <h2>Custom Theme</h2>
  </my-card>

Reactive Theming with the style Export

Coralite takes this a step further with the style export. It allows you to reactively compute CSS variables based on the component's internal state.

javascript
Code copied!
  <script type="module">
    export const attributes = {
      status: { type: String, default: 'info' }
    }
  
    export const style = {
      // Reactively compute the background based on the status attribute
      '--card-bg': ({ state }) => {
        if (state.status === 'error') return '#EF4444'
        if (state.status === 'success') return '#10B981'
        return 'var(--bg-card)'
      }
    }
  </script>

Why this matters

This pattern eliminates the need for complex JavaScript theme providers or Context APIs. The browser's native CSS engine handles the styling, while Coralite handles the reactive state.