将样式应用于浏览器自己的元素,还是原生的Shadow DOM?

时间:2013-11-18 09:14:07

标签: css browser css-selectors web-component shadow-dom

在Rob Dodson谈论Web Components之后,他提到了全新的#cat;#34; ^^和"帽子" ^ CSS选择器,我已经询问过将样式应用于自定义元素的ShadowDOM的可能性,以及浏览器的原生元素' ShadowDOM?

是否可以设置ShadowDOM中的元素样式?在哪些浏览器中如何? 我发现的唯一相关文章是Dimitry Glazkov在&#39; What the Heck is Shadow DOM?&#39;,他在那里通过使用伪选择器和-webkit-appearance: none;规则来达到ShadowDOM子树。< / p>

2 个答案:

答案 0 :(得分:2)

由于CSS Scoping Module Level 1草案的状态随时可以改变,我原来的方法工作时间不长。

Chrome v33 + 中,您必须在Enable Experimental Web Platform Features开启chrome://flags才能使以下代码生效。


Chrome Canary v33 及其猫选择器^^开始,答案是:是!
更新2014-03-30: Chrome Canary v35 + 支持最新版本的选择器,现在称为/deep/ selector

它适用于所有边界,也适用于原生元素。

请参阅:http://codepen.io/Volker_E/pen/jsHFC

/* ... Example for applying to all h2 elements, no matter if DOM or any ShadowDOM subtree ... */
:root ^^ h2 {
    font-family: "Arial Black", sans-serif;
}

/* Cr 33+: The "cat" also works on native elements' ShadowDOM */
video ^^ input[type="button"]:first-child {
    opacity: .75;
    -webkit-filter: drop-shadow( .2rem .2rem .2rem hsla( 5, 100%, 50%, 1 ) );
}

/* Cr 35+: /deep/ also works on native elements' ShadowDOM */
video /deep/ input[type="button"]:first-child {
    opacity: .75;
    -webkit-filter: drop-shadow( .2rem .2rem .2rem hsla( 5, 100%, 50%, 1 ) );
}

答案 1 :(得分:1)

至少在Chrome中,这是可能的。如果您检查<input type="date">的Shadow DOM,您会看到:

<input type="date">
  #document-fragment
    <div part="-webkit-datetime-edit" id="date-time-edit">
      <div part="-webkit-datetime-edit-fields-wrapper">
        <span role="spinbutton" aria-valuetext="blank" aria-valuemin="1" aria-valuemax="12" aria-help="Month" part="-webkit-datetime-edit-month-field">mm</span>
        <div part="-webkit-datetime-edit-text">/</div>
        <span role="spinbutton" aria-valuetext="blank" aria-valuemin="1" aria-valuemax="31" aria-help="Day" part="-webkit-datetime-edit-day-field">dd</span>
        <div part="-webkit-datetime-edit-text">/</div>
        <span role="spinbutton" aria-valuetext="blank" aria-valuemin="1" aria-valuemax="275760" aria-help="Year" part="-webkit-datetime-edit-year-field">yyyy</span>
      </div>
    </div>
</input>

然后你可以设置单独的伪元素样式:

::-webkit-datetime-edit-year-field {
  font-weight: bold;
}

According to Rob Dodson himself可以使用^^^选择器来设置原生Shadow DOM的样式。所以这个规则应该有效(Chrome Canary,我相信):

input[type="date"] ^ [part="-webkit-datetime-edit-year-field"] {
  font-weight: bold;
}