🔰slotted node styles
╱🚧 under construction -> CSS 繼承
web ⟩ component ⟩ slot ⟩ slotted node styles
MDN ⟩ CSS ⟩ Pseudo-elements
Gemini ⟩ How to style slotted nodes?
控制樣式的方式
📁 <template> 內部 CSS:用::slotted() (pseudo-element)
<template id="my-component-template">
<style>
/* ⭐️ slotted: <p> element */
::slotted(p) { ... }
/* ⭐️ slotted: all nodes */
::slotted(*) { ... }
/* ⭐️ slotted: class="highlight" */
::slotted(.highlight) { ... }
</style>
<slot></slot>
</template>⚠️ 但 ::slotted() 有限制:
只能設定部分樣式,如:
font、text、margin、padding、border、background等。較複雜的樣式可能無法運作,如:
display、float、width、height等。無法選擇後代元素。如:
::slotted(p span)是無效的。
📁 外部 CSS:slotted nodes 會繼承外部的 CSS 樣式
<style>
/* 選擇 my-component 內的所有 <p> 元素(不是直接子元素也包含) */
/* ⭐️ ::slotted(p) 只能選擇 `my-component > p` ❗ */
my-component p { ... }
/* 選擇 <my-component> 的直接子元素,也就是 slotted nodes */
/* 相當於 ::slotted(*) */
my-component > * { ... }
</style>📁 <template> 內部 CSS:
<template id="my-component-template">
<style>
/* :host 選擇 component 本身 */
:host {
/* ⭐️ 內部定義要使用的 CSS 變數 */
--text-color: blue;
}
</style>
<slot></slot>
</template>📁 外部 CSS:
my-component p {
/* ⭐️ 外部使用已定義的 CSS 變數 */
color: var(--text-color); /* CSS 會使用定義在 :host 的變數 */
}嚴格上說來,這也是一種 CSS 繼承。
Last updated
Was this helpful?