Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply styles from parent

Suppose I have a component with this template:

<div class="frame">
  <span class="user-defined-text">{{text}}</span>
</div>
<style>
  span { font-size: 3em; }
  .frame { ... }
</style>

How can I merge the styles applied to the component, e.g.

<custom-component [text]="'Some text'">
<style>custom-component { font-weight: bold; }</style>

so that the final output "Some text" is both bold and 3em sized?

Even better is there a way to get the computed styles for the host element, so that, for example, I could apply the background-color of the host to the border-color of some element in my template?

like image 650
Soumya Avatar asked Jan 29 '16 05:01

Soumya


People also ask

How do I apply CSS from parent to child?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors.

Is there a CSS parent selector?

Let's be clear here, just in case someone is finding this from a search engine: there are no parent selectors in CSS, not even in CSS3.

How do I traverse from parent to child in CSS?

In a css selector if we need to traverse from parent to child we use > symbol. To get all the immediate children we have to specify * symbol after parent node in the css expression. So the customized css should be parent > *. So for a <ul class="toc chapter">, the css for immediate children shall be ul.

What is a parent child selector when would this be useful?

The ("parent > child") selector selects all elements that are a direct child of the specified element.


2 Answers

  • set encapsulation: ViewEncapsulation.None to allow styles from outside to be applied.
import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'custom-component',
  encapsulation: ViewEncapsulation.None
})
export class Custom {
  • use styleUrl to add a CSS file in combination with host selector
:host(.someClass) {
      background-color: blue;
}

<custom-component class="someClass"></custom-component>

to apply styles depending on the class added to the element.

like image 60
Günter Zöchbauer Avatar answered Oct 02 '22 06:10

Günter Zöchbauer


I know this is old, but I feel this should be more visible. You could use the /deep/ selector to force a style down through the child component tree into all the child component views. The /deep/ selector works to any depth of nested components, and it applies both to the view children and the content children of the component.

I feel this is much cleaner and easier to implement.

parent.css

/deep/ .class {
    background-color: red;
}

https://angular.io/docs/ts/latest/guide/component-styles.html

like image 41
Mike Avatar answered Oct 02 '22 07:10

Mike