Max888
Max888

Reputation: 3770

Web Components - extend native element's style

I would like to extend the native button element but I am not sure how to add styling. In Google's example here they don't use a template so the fancy-button custom element itself is the button, rather than adding a template and shadow DOM containing a button element. It seems to defeat the object of extending a native element if I just add a button directly to the shadow DOM, but I don't know how to style and extend native element. How can I create a custom element which is simply the native button element extended to have a red background?

var style = `button { background-color: red; };
class FancyButton extends HTMLButtonElement {
  constructor() {
    super();
  }
customElements.define('fancy-button', FancyButton, {extends: 'button'});

Upvotes: 1

Views: 1470

Answers (1)

  1. since you don't have shadowDOM involved you can use global CSS
  2. you can set styles in the connectedCallback: this.style.background='red'
  3. you can dynamically create a STYLE tag with unique identifier scoping your element

See JSFiddle for all 3 examples: https://jsfiddle.net/WebComponents/gohzwvL4/

Important is the notation for your Customized Built-In Element

Correct : <button is="fancy-button></button>

InCorrect: <fancy-button></fancy-button> (this is Autonomous Element notation)

.

Firefox pitfall:

The INcorrect notation works in Firefox , but not in Chrome & Opera

Firefox processes Extended Built-In Elements with Autonomous Element notation
but only for elements created in the DOM prior to definition:

This

<fancy-button>Hello Fancy Red Button #1</fancy-button>

<script>
    class FancyButton extends HTMLButtonElement {
        constructor() {
            super();
        }

        connectedCallback() {
            this.style.background = 'red';
        }
    }

    customElements.define('fancy-button', FancyButton, { extends: 'button' });
</script>

<fancy-button>Hello Fancy Red Button #2</fancy-button>

is displayed in Firefox as:

  • any number of Custom Elements before the SCRIPT tag are colored!

  • When the <SCRIPT> is moved into the <HEAD> Firefox won't color any background

  • When the script is executed after the onload event all buttons are colored

This is non-standard behaviour!

Upvotes: 2

Related Questions