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?
Asked
Active
Viewed 1.8k times
25

DongBin Kim
- 1,799
- 5
- 23
- 43
1 Answers
42
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;
}

ConnorsFan
- 70,558
- 13
- 122
- 146
-
Is there any reason that the :host display should be inline? Would it have any unwanted effect if it's changed to block? – Apr 01 '20 at 20:27
-
1@QianChen - The host element is `inline` by default but that can be changed. The only side effect that I know is on the layout, which is what we want here. You can also choose `inline-block`, to preserve the ability to insert the component in a line. – ConnorsFan Apr 01 '20 at 20:40
-
Should I add it to every component? Can I add it somewhere to apply it globally – Volodymyr Bilovus Jan 20 '22 at 17:14