主题开发文档

💡 云策文档标注

概述

theme.json 中的 styles 属性用于在全局、元素和块级别配置样式设置。WordPress 支持 CSS 规范的标准子集,并允许直接在 theme.json 中添加自定义 CSS。建议优先使用 styles 属性添加主题样式,以便用户通过外观 > 编辑器 > 样式进行自定义,避免 CSS 特异性问题。

关键要点

  • styles 是 theme.json 的顶级属性,包含嵌套属性如 elements 和 blocks,用于分层配置样式。
  • WordPress 支持标准 CSS 子集,并允许在 theme.json 中直接添加自定义 CSS,提升样式管理效率。
  • 推荐通过 styles 属性添加主题样式,特别是标准 WordPress 功能,以支持用户通过站点编辑器进行无冲突自定义。
  • 文档提供链接,帮助开发者学习可用样式属性及如何通过 theme.json 应用样式。

代码示例

{
	"version": 2,
	"styles": {
		"color": {
			"text": "#000000",
			"background": "#ffffff"
		},
		"elements": {
			"button": {
				"color": {
					"text": "#ffffff",
					"background": "#000000"
				}
			}
		},
		"blocks": {
			"core/code": {
				"color": {
					"text": "#ffffff",
					"background": "#000000"
				}
			}
		}
	}
}

📄 原文内容

The styles property in theme.json lets you configure settings at the global level, for individual elements, and individual blocks. WordPress supports a standard subset of the CSS specification, but also allows you to add custom CSS directly in your theme.json file.

When possible, it is recommended to add your theme styles via the styles property, at least for standard WordPress features. This makes it possible for users to customize them via Appearance > Editor > Styles without CSS specificity issues.

This document contains links for learning about the available style properties and how to apply styles to your theme via its theme.json file.

The styles property

styles is a top-level property in theme.json and has multiple nested properties that you can define. And some of those nested properties have multiple levels of nesting of their own.

The following is an overarching look at these properties in the context of a theme.json file:

{
	"version": 2,
	"styles": {
		"elements": {},
		"blocks": {}
	}
}

The following is an example of what the styles property could look like in a custom theme.json file. This should give you a feel for how it is structured, but you will dive into this more deeply as you read through this section of the handbook:

{
	"version": 2,
	"styles": {
		"color": {
			"text": "#000000",
			"background": "#ffffff"
		},
		"elements": {
			"button": {
				"color": {
					"text": "#ffffff",
					"background": "#000000"
				}
			}
		},
		"blocks": {
			"core/code": {
				"color": {
					"text": "#ffffff",
					"background": "#000000"
				}
			}
		}
	}
}

Styles documentation

Use the following links to explore configuring styles via theme.json file:

  • Applying Styles: How to apply custom styles to your theme using the standard JSON syntax.
  • Using Presets: How to use the presets that you’ve configured via the settings property in your styles.
  • Styles Reference: A reference guide for the available style properties that you can use in theme.json.