大网数据广告活动
Web 标准与前端开发

CSSStyleSheet: CSSStyleSheet() constructor

· 52CE 我爱测

The **`CSSStyleSheet()`** constructor creates a new CSSStyleSheet object which represents a single Stylesheet.

CSSOM

The CSSStyleSheet() constructor creates a new CSSStyleSheet object which represents a single Stylesheet.

After constructing a stylesheet the CSSStyleSheet.replace(), CSSStyleSheet.replaceSync(), CSSStyleSheet.insertRule(), and CSSStyleSheet.deleteRule() methods can be used to modify the rules of the new stylesheet.

A stylesheet created using this method is referred to as a "constructed stylesheet". A constructed stylesheet can be shared between a document and its shadow DOM subtrees using ShadowRoot.adoptedStyleSheets and Document.adoptedStyleSheets.

Syntax

new CSSStyleSheet()
new CSSStyleSheet(options)

Parameters

  • options
    • : An object containing the following:
      • baseURL
        • : A string containing the baseURL used to resolve relative URLs in the stylesheet.
      • media
        • : A MediaList containing a list of media rules, or a string containing a single rule.
      • disabled
        • : A Boolean indicating whether the stylesheet is disabled. False by default.

Examples

In the following example, a new CSSStyleSheet is constructed with a media rule of "print". Printing StyleSheet.media to the console returns a MediaList with a single entry for this print rule.

let stylesheet = new CSSStyleSheet({ media: "print" });
console.log(stylesheet.media);

Sharing stylesheets with a shadow DOM

The code below shows the sheet being constructed and then CSSStyleSheet.replaceSync() is called to add a rule to the sheet.

// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");

We then create a ShadowRoot and pass the sheet object to the ShadowRoot.adoptedStyleSheets property inside an array.

// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });

// Adopt the sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];

We can modify the stylesheets after they have been added to the array. Below we append a new rule to the same sheet using CSSStyleSheet.insertRule().

sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.

The same sheet can be shared with multiple shadow subtrees in the same document. For more examples see ShadowRoot.adoptedStyleSheets.

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。