Search code examples
javascripthtmlcsstypescriptcustom-element

HTML custom element has no width


I created custom element and set its dimensions and background color. But in page it dont render anything. In DOM it is present, but not visible.

export class BaseLayout extends HTMLElement{
    constructor() {
        super();
        this.style.backgroundColor="red";
        this.style.width = "500px";
        this.style.height = "500px";
    }
}
customElements.define("base-layout", BaseLayout);

When I add something (via innerText), red background appear, but only as background to that text (and not for 500px width and height).

One way I solved it is to extends HTMLDivElement instead of HTMLElement. But when I do this, I lost my fancy custom html tags (it will be replaced by DIV). Is there way to avoid that?

Thanks!


Solution

  • You just have to set its display property to something like 'block' or 'inline-block'.

    this.style.display = 'block';
    

    So, your example would look like this:

    export class BaseLayout extends HTMLElement{
        constructor() {
            super();
            this.style.backgroundColor="red";
            this.style.width = "500px";
            this.style.height = "500px";
            this.style.display = "block";
        }
    }
    customElements.define("base-layout", BaseLayout);