ayoayco / web-component-base

Web Components in Easy Mode 🧱
https://WebComponent.io
MIT License
71 stars 2 forks source link

feat: scoped styles #31

Closed ayoayco closed 11 months ago

ayoayco commented 11 months ago

When using the built-in html function for tagged templates, a style object of type Partial<CSSStyleDeclaration> can be passed to any element's style attribute. This allows for calculated and conditional styles. Read more on style objects on MDN

import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";

class StyledElements extends WebComponent {
  static props = {
    condition: false,
    type: "warn",
  };

  #typeStyles = {
    warn: {
      backgroundColor: "yellow",
      border: "1px solid orange",
    },
    error: {
      backgroundColor: "orange",
      border: "1px solid red",
    },
  };

  get template() {
    return html`
      <div
        style=${{
          ...this.#typeStyles[this.props.type],
          padding: "1em",
        }}
      >
        <p style=${{ fontStyle: this.props.condition && "italic" }}>Wow!</p>
      </div>
    `;
  }
}

customElements.define("styled-elements", StyledElements);

fixes #30 fixes #29

vercel[bot] commented 11 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
web-component-base ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 18, 2023 3:56pm