Styling Components Using :host CSS Selector

Hi, I'm a seasoned software engineer with over 11 years of experience in the industry. Currently, I'm part of the talented team at Deloitte. My expertise lies in crafting beautiful and responsive web experiences using CSS and HTML. When I'm not coding, you'll find me capturing moments through my lens – photography is my creative escape. And whenever wanderlust strikes, I'm ready to explore new places and cultures.
Use the :host pseudo-class selector to target styles in the element that hosts the component (as opposed to targeting elements inside the component’s template).
Source:
<!-- demo.component.html -->
Demo component!
<!-- demo.component.css -->
:host {
display: block;
border: 1px solid black;
}
Result:

The :host selector is the only way to target the host element. You can’t reach the host element from inside the component with other selectors because it’s not part of the component’s own template. The host element is in a parent component’s template.
Use the function form to apply host styles conditionally by including another selector inside parentheses after :host.
The next example targets the host element again, but only when it also has the active CSS class.
Source:
<!-- app.component.html -->
<app-demo></app-demo>
<app-demo class="active"></app-demo>
<!-- demo.component.html -->
Demo component!
/* demo.component.css */
:host {
display: block;
border: 1px solid black;
}
:host(.active) {
border-width: 3px;
}
Result:
Thanks, Keep learning!



