:host()
Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
CSS 伪类函数 :host()
选择包含使用这段 CSS 的 Shadow DOM 的影子宿主(这样就可以从 Shadow DOM 中选择包括它的自定义元素)——但前提是该函数的参数与选择的阴影宿主相匹配。
最简单的用法是仅将类名放在某些自定义元素实例上,然后将相关的类选择器作为函数参数包含在内。不能将它与后代选择器表达式一起使用,以仅选择特定祖先内部的自定义元素的实例。这是 :host-context()
的作用。
备注: 在 shadow DOM 之外使用时,这没有任何效果。
/* 选择阴影根元素,仅当它与选择器参数匹配 */
:host(.special-custom-element) {
font-weight: bold;
}
语法
:host( <compound-selector> )
示例
在这个例子中,有一个简单的自定义元素 <context-span>
可以用它包裹文本:
<h1>Host selectors <a href="#"><context-span>example</context-span></a></h1>
在元素的构造函数中,创建style
和span
元素,填充span
自定义元素的内容,并style
使用一些 CSS 规则填充元素:
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(.footer) { color : red; }
规则为文档中所有在其上设置了 footer
类的<context-span>
元素实例(此实例中的影子宿主)设置样式——使用它来为 <footer>
中的元素提供实例一种特殊的颜色。
规范
Specification |
---|
CSS Scoping Module Level 1 # host-selector |
浏览器兼容性
BCD tables only load in the browser