Skip to content Skip to sidebar Skip to footer

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

Solution 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/CustomElementsExamples/Lf829wpy/

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>classFancyButtonextendsHTMLButtonElement {
        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!

Post a Comment for "Web Components - Extend Native Element's Style"