简体   繁体   English

HTML 自定义元素没有宽度

[英]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.在 DOM 中它存在,但不可见。

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).当我添加一些东西(通过innerText)时,会出现红色背景,但仅作为该文本的背景(而不是500px的宽度和高度)。

One way I solved it is to extends HTMLDivElement instead of HTMLElement.我解决它的一种方法是扩展 HTMLDivElement 而不是 HTMLElement。 But when I do this, I lost my fancy custom html tags (it will be replaced by DIV).但是当我这样做时,我失去了我喜欢的自定义 html 标签(它将被 DIV 取代)。 Is there way to avoid that?有没有办法避免这种情况?

Thanks!谢谢!

You just have to set its display property to something like 'block' or 'inline-block' .您只需要将其display属性设置为'block''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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM