Angular component host element width and height ar

2020-02-12 02:09发布

问题:

When I inspect my component element, sometimes its width and height are 0 even though if I inspect inside, the elements the component include have a certain width and height. This leads me not to able to style the host element because even when I set width and height to the host element by declaring :host { // styles } it doesn't work. So I ended up adding an extra div wrapping around the component element to give some width and height which I find it verbose. Is it a natural thing? Or am I missing something?

回答1:

From what I can see by inspecting a rendered Angular component in the browser, the host element has the attribute display: inline by default. As mentioned in a few questions (1, 2), the size of inline elements cannot be changed with CSS styles.

In order for the width and height style attributes to be effective, you should set the display attribute of the host element to block or inline-block:

display: block;
display: inline-block;

You can see an example in this stackblitz, where the following CSS is used:

:host {
    display: inline-block;
    width: 300px;
    height: 200px;
    background-color: orange;
}


标签: angular