Using CSS counter-reset in :host declaration of a Custom Element

有些话、适合烂在心里 提交于 2019-12-02 02:09:50

:host is a pseudo-class that selects the shadow host element (that is: the HTML element that hosts the Shadow DOM), not the shadow root.

As a consequence, a counter-reset will affect the counter in the main DOM tree, not the counter in the Shadow DOM (see the example below).

If you want to set a CSS counter in the Shadow DOM root, you could use the :first-of-type selector:

 div:first-of-type {
    counter-reset: squarenr -1
 }

window.customElements.define('game-toes', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'closed'})
     .appendChild(document.querySelector('#Styles').content.cloneNode(true));
  }
});
div::after {
  counter-increment: squarenr ;
  content: counter( squarenr ) ;
}
<TEMPLATE id="Styles">
  <STYLE>
      :host {
        display: grid;
        grid-template: repeat(3, 1fr) / repeat(3, 1fr);
        grid-gap: .5em;
        counter-reset: squarenr -1; 
      }
      :host > div:first-of-type {
        counter-reset: squarenr -1; 
        color: red;
      }
      DIV {
        font-size:2em;
        display:flex;
        justify-content:center;
        background:lightgrey;
        counter-increment: squarenr  ;
      }
      #_::before {
        background:lightgreen;
        content: counter(squarenr);
      }
      #X::after,
      #O::after {
        content: attr(id);
      }
  </STYLE>
  <DIV id=_></DIV><DIV id=_></DIV><DIV id=X></DIV>
  <DIV id=_></DIV><DIV id=X></DIV><DIV id=_></DIV>
  <DIV id=O></DIV><DIV id=O></DIV><DIV id=X></DIV>
</TEMPLATE>
<div>squarenr=</div><game-toes></game-toes><div>squarenr=</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!