:host CSS伪类选择包含其内部使用的CSS的shadow DOM的根元素 - 换句话说,这允许你从其shadow DOM中选择一个自定义元素。

注意:在shadow DOM之外使用时,这没有任何效果。

/* Selects a shadow root host */
:host {
  font-weight: bold;
}

语法

该属性的语法尚未添加

示例

以下片段取自我们的 host-selectors 示例(在线演示)。

在这个例子中,我们有一个简单的自定义元素 — <context-span> — 你可以包裹文本:

<h1>Host selectors <a href="#"><context-span>example</context-span></a></h1>

在元素的构造函数中,我们创建stylespan元素,用自定义元素的内容填充span,并使用一些CSS规则填充style 元素:

let style = document.createElement('style');
let span = document.createElement('span');
span.textContent = this.textContent;

const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(style);
shadowRoot.appendChild(span);

style.textContent = 'span:hover { text-decoration: underline; }' +
                    ':host-context(h1) { font-style: italic; }' +
                    ':host-context(h1):after { content: " - no links in headers!" }' +
                    ':host-context(article, aside) { color: gray; }' +
                    ':host(.footer) { color : red; }' +
                    ':host { background: rgba(0,0,0,0.1); padding: 2px 5px; }';

:host { background: rgba(0,0,0,0.1); padding: 2px 5px; } 规则设置<context-span>元素的所有实例的样式(此实例中为影子根元素)的所有实例。

规范

Specification Status Comment
CSS Scoping Module Level 1
:host
Working Draft Initial definition.

浏览器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
:hostChrome Full support YesEdge No support No
Notes
No support No
Notes
Notes Under consideration
Firefox Full support 63
Full support 63
No support 61 — 63
Disabled
Disabled From version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile No support No
Notes
No support No
Notes
Notes Under consideration
Firefox Android Full support 63
Full support 63
No support 61 — 63
Disabled
Disabled From version 61 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

参见

文档标签和贡献者

标签: 
此页面的贡献者: zhangchen
最后编辑者: zhangchen,