shadow DOM styles

Web ComponentsShadow DOM

:host, :host(), :host-context(), ::slotted()

:host, :host(), :host-context() only works in the context of a shadow root, you can't use it outside of shadow DOM.

/* ⭐️ select host element (from inside shadow DOM) */
:host {

  /* ⭐️ by default, custom elements are `display: inline` */
  display: block;
  
  /* CSS containment */ 
  contain: content; 
}

:host {
  opacity: 0.4;
  will-change: opacity;
  transition: opacity 300ms ease-in-out;
}

/*
  ⭐️ :host(<selector>) ⭐️
     -----------------
     target the host if it matches a <selector>. 
*/
:host(:hover) {
  opacity: 1;
}

:host([disabled]) { /* style when host has disabled attribute. */
  background: grey;
  pointer-events: none;
  opacity: 0.4;
}

:host(.blue) {
  color: blue; /* color host when it has class="blue" */
}

:host(.pink) > #tabs {
  color: pink; /* color internal #tabs node when host has class="pink". */
}

⭐️ 注意:

  • 如果同時在 shadow DOMlight DOM 中分別用 :hostcustom-element selector 對 <custom-element> 做 CSS 格式設定,則外部的格式具有優先權

  • 我們可以利用這種特性,使用 :host<custom-element> 設定預設格式,然後在外部的 CSS 中再使用 custom-element 設定自訂格式

Topics

Examples

Last updated