문제

I have to apply special CSS style to my web component if it's a direct child of <body> element. Here is what I've tried so far:

/* applies even if the component isn't a direct child */
:host(body) {
    color: red;
}

/* never applies */
:host(body:host) {
    color: red;
}

/* never applies */    
:host(body:host > my-component) {
    color: red;
}

/* never applies */    
:host(body > my-component:host) {
    color: red;
}

Browsers: Chrome Stable (32.0.1700.107), Chrome Canary (34.0.1843.3).

도움이 되었습니까?

해결책

I don't think this is currently possible without a parent selector in CSS.

You could do something like this in Chrome 32:

/* @polyfill body > :host h1 */

This works in Chrome 32 because the @polyfill directive adds a document level style that says: body > polymer-foo h1. However, this does not work in Chrome 34 because document level styles are ignored by the Shadow DOM.

Also, :host will now only match the host element itself. If you want to try matching the ancestor you can use :ancestor(). Unfortunately :ancestor(body) > :host h1 will not work. :ancestor(body) gets translated to any node which is a descendant of body so the above snippet would be rewritten as polymer-foo > polymer-foo h1.

It's disappointing that this is not possible today but Shadow DOM styles are still in their infancy and hopefully we'll be able to be more expressive in the future.

For future reference, the work in progress spec on Shadow DOM styling can be found here: http://dev.w3.org/csswg/shadow-styling

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top