---
title: CSS Shadow Parts:part 与 slotted 样式出口
keywords:
- ::part
- ::slotted
- Shadow DOM
- 样式出口
- 组件主题化
description: 说明 Shadow DOM 的样式出口:::part(name) 与 ::slotted(selector) 的作用与差异,如何在不破坏封装的前提下对内部元素进行主题化与样式覆盖,提供示例与兼容建议。
categories:
- 文章资讯
- 编程技术
---
概述
Shadow DOM 默认样式隔离。::part(name) 将内部元素标记为可被外部样式覆盖的“出口部件”;::slotted(selector) 用于为插槽分发的外部内容设置样式。合理使用这两者可在保持封装的前提下实现主题化。
示例
<!-- 组件内部 -->
<template id="tpl">
<style>
.btn { padding: 8px 12px; border-radius: 8px }
.btn::part(icon) { /* 内部定义可导出的部件 */ }
</style>
<button class="btn"><span part="icon">★</span><slot></slot></button>
</template>
<script>
customElements.define('x-button', class extends HTMLElement {
constructor(){ super(); const root=this.attachShadow({mode:'open'}); root.append(document.getElementById('tpl').content.cloneNode(true)) }
})
</script>
<!-- 外部使用 -->
<x-button>确定</x-button>
<style>
x-button::part(icon){ color: #e11 }
x-button::slotted(span.badge){ margin-left: 4px; background: #eee }
</style>
工程建议
- 颗粒度:为需要主题化的内部元素添加
part名称;避免过度暴露破坏封装。 - 与封装:
::part仅能匹配带part的内部元素;::slotted仅影响分发到插槽的外部内容。 - 兼容:在不支持环境回退到自定义属性/类名配置;保持 API 一致性。
参考与验证
- MDN
::part文档:https://developer.mozilla.org/docs/Web/CSS/::part - MDN
::slotted文档:https://developer.mozilla.org/docs/Web/CSS/::slotted - Web Components 指南:https://developer.chrome.com/docs/web-platform/web-components/

发表评论 取消回复