Home > Web Front-end > CSS Tutorial > Managing CSS Styles in a WordPress Block Theme

Managing CSS Styles in a WordPress Block Theme

Christopher Nolan
Release: 2025-03-10 10:01:09
Original
138 people have browsed it

Managing CSS Styles in a WordPress Block Theme

How CSS is written in WordPress themes is changing dramatically. I recently shared a technology that adds fluid font support in WordPress via theme.json, a new document that is heavily promoted by WordPress that will become the central source of truth for defining WordPress theme styles that support Site-Whole Editing (FSE) functionality.

Wait, no style.css file? We still have it. In fact, style.css is still a necessary file in a block theme, although it has a much reduced effect and is only used to register meta-information for the topic. That is, theme.json is still under active development, which means we are in a transitional period where you may find styles defined at theme.json, styles.css and even block levels.

So, what are the styles actually like in these WordPress FSE eras? This is what I want to introduce in this article. The WordPress theme developer manual lacks documentation on block theme styles, so everything we’ve covered here is information I’ve collected about the current situation and future discussions on WordPress themes.

Evolution of WordPress Style

The new development features included in WordPress 6.1 bring us closer to a system that defines styles entirely in theme.json, but there is still a lot of work to do before we can rely on it completely. We can learn what will appear in future releases by using the Gutenberg plugin, where experimental features are usually tested.

We can also learn about our current status by looking at the evolution of the default WordPress theme. So far, there are three default themes that support site-wide editing:

  • Twenty Twenty-One (TT1): This is the first classic default theme version that is compatible with blocks. There is also a block version (TT1 block) and has been a reliable resource for block themes since then. However, all 5900 rows of CSS in TT1 are in style.css. No theme.json file. TT1 block is the first time we have seen styles in the block editor era, which we can think of as trailer rather than model.
  • Twenty Twenty-Two (TT2): This is the first truly block-based default WordPress theme and the first time we encountered theme.json. This file contains only 373 lines of code. Its main developers have made coordinated efforts to make it a CSS-free theme; however, style.css still comes with less than 150 lines of code, as not all theme.json issues are resolved in the experimental Gutenberg plugin before release.
  • Twenty Twenty-Three (TT3): This is published in WordPress 6.1 and it is the first theme example without any CSS in the required style.css file.

However, do not immediately replace the CSS in style.css with the JSON attribute-value pair in theme.json. Before considering doing this, there are still some CSS style rules to support in theme.json. The remaining important issues are currently being discussed, the goal is to move all CSS style rules into theme.json completely and merge different sources of theme.json into one UI to set up global styles directly in the WordPress site editor.

This puts us in a relatively difficult situation. Not only is there no clear path to override the theme styles, but it is also unclear what the styles are from - are they from different layers of theme.json files, style.css, Gutenberg plugin or elsewhere?

Why choose theme.json instead of style.css?

You may be wondering why WordPress turns to JSON-based style definitions instead of traditional CSS files. Ben Dwyer of Gutenberg's development team eloquently explains why the theme.json method is a benefit for topic developers.

Worth reading Ben's post, but the point is in this quote:

Whether it is layout, preset or block style, overwriting CSS can pose a barrier to integration and interoperability: visual consistency between the front-end and the editor becomes more difficult to maintain, and upgrading within the block may conflict with override. Additionally, custom CSS is less portable in other block themes.

The hierarchy of the "Basics" defined styles can be correctly solved by encouraging topic authors to use the theme.json API as much as possible.

One of the main benefits of moving CSS to JSON is that JSON is a machine-readable format, which means it can be exposed in the WordPress site editor UI by getting the API, allowing users to modify the default values ​​and customize the appearance of the site without writing any CSS. It also provides a way to style blocks consistently, while providing a structure that creates a specific layer so that user settings have higher priority than settings defined in theme.json. This interaction between theme-level styles in theme.json and user-defined styles in global style UI makes the JSON method so attractive.

Developers maintain consistency in JSON, and users gain flexibility through codeless customization. This is a win-win situation.

Of course, there are other benefits, and WP Engine's Mike McAlister lists several in this Twitter thread. You can find more benefits in the in-depth discussion on the Make WordPress Core blog. After reading, compare the advantages of the JSON method with the available methods that define and overwrite styles in classic topics.

Define styles using JSON elements

We have seen a lot of progress in terms of what parts of the theme can be set. Before WordPress 6.1, all we could really do was style the title and link. Now, with WordPress 6.1, we can add buttons, titles, quotes, and titles. theme.json

We do this by defining the

JSON element. An element can be treated as a single component that exists in a WordPress block. Suppose we have a block with the title, paragraph, and buttons. These individual parts are elements, and there is an object in which we define their style: theme.json elements

A better way to describe JSON elements is to be low-level components of topics and blocks, which do not require block complexity. They are representations of HTML primitives that are not defined in blocks but can be used between blocks. How they are supported in WordPress (and Gutenberg plug-in) is described in the Block Editor manual and in this site-wide editing tutorial by Carolina Nymark.
<code>{
  "version": 2,
  "settings": {},
  // etc.
  "styles": {
    // etc.
    "elements": {
        "button": { ... },
        "h1": { ... },
        "heading": { ... },
    },
  },
  "templateParts": {}
}</code>
Copy after login
Copy after login

For example, the link styles in the

object, but is not a block itself. But the link can be used in a block, it will inherit the style defined in the

object of elements. But this does not completely summarize the definition of elements, as some elements are also registered as blocks, such as title and button blocks - but these blocks can still be used in other blocks. theme.json elements.linkThe following is the table of elements provided by Carolina that can be used to style in

before WordPress 6.1:

theme.json As you can see, this is still in its early stages and there is still a lot of things to move from the Gutenberg plugin to the WordPress core. But you can see how fast it would be to globally set all titles in the theme without searching for selectors in CSS files or DevTools.

In addition, you can start to understand how the structure of theme.json forms a specific layer, from global elements (such as titles) to individual elements (such as h1), and block-level styles (such as h1 included in a block).

For more information on JSON elements, see this Make WordPress proposal and this open ticket in the Gutenberg plugin GitHub repository.

JSON and CSS specificity

Let's continue to discuss CSS specificity. As I mentioned earlier, JSON's style method creates a hierarchy. This is true. Styles defined on JSON elements in theme.json are considered as the default theme style. Anything set by the user in the global style UI will override the default value.

In other words: User styles have higher specificity than default theme styles. Let's take a look at the button block to understand how it works.

I use Emptytheme, which is a blank WordPress theme without CSS style. I'll add a button block to the new page.

OK, we know that WordPress core comes with some simple styles. Now, I will switch to the default TT3 theme in WordPress 6.1 and activate it. If I refresh the page with the button, the style of the button changes.

You can see exactly where these new styles are from in the

file of TT3. This tells us that JSON element styles take precedence over WordPress core styles. theme.json

Now I will modify TT3 by overwriting it in the child theme, where the default background color of the button block is set to red.

But please note the search button in the last screenshot. It should be red, too, right? This means that if the changes I made are at the global level, then it must be styled at another level. If we want to change the

two buttons, we can make changes at the user level using the global style UI in the site editor.

We used the global style UI to change the background color of the two buttons to blue and modified the text. Note that the blue there takes precedence over the theme style!

Style Engine

This is a very fast but good idea about how to manage CSS specificity in WordPress block themes. But this is not the complete picture, because it is not clear where these styles are generated. WordPress has its own default styles that come from somewhere, use the data in

to get more style rules and overwrite those rules with whatever is set in the global style. Are these styles inlined? Are they in separate stylesheets? Maybe they were injected on the page? theme.json

This is the problem that the new style engine is expected to solve. The Style Engine is a new API in WordPress 6.1, aiming to keep the styles generated and the application location of the styles consistent. In other words, it takes all possible style sources and is individually responsible for correctly generating block styles. I know, I know. Just to write some styles, an abstraction layer was added on top of other abstraction layers. However, having a centralized style API is probably the most elegant solution, given that styles can come from multiple places.

We are only seeing the style engine for the first time. In fact, according to the ticket, the following work has been done so far:

  • Audit and merge backend generate blocks that support CSS code locations so that they are delivered from the same location (rather than multiple locations). This includes CSS rules such as margins, fills, typography, colors, and borders.
  • Remove duplicate layout-specific styles and generate semantic class names.
  • Reduce the number of inline style tags that support printing to pages to blocks, layouts, and elements.

Basically, this is the basis for building a single API that contains all the CSS style rules for the topic, no matter where they come from. It cleans up the way WordPress injects inline styles before 6.1 and builds a system for semantic class names.

For more details on the long-term and short-term goals of style engines, see this Make WordPress Core discussion. You can also follow tracking issues and project boards for more updates.

Using JSON elements

We discussed the HTML primitives in the theme.jsonJSON elements in the file and how they basically define the default style of content such as titles, buttons, and links. Now let's see how the actual uses JSON element and how it behaves in various style contexts.

JSON elements usually have two contexts: global level and block level. The definition of global level styles is lower than the block level to ensure block-specific styles are preferred so that consistency is maintained anywhere the block is used.

Global Style of JSON Element

Let's take a look at the new default TT3 theme and check the style of its buttons. Here is a short copy-paste of the TT3 theme.json file (this is the full code), showing the global style section, but you can find the original code here.

View code ``` { "version": 2, "settings": {}, // ... "styles": { // ... "elements": { "button": { "border": { "radius": "0" }, "color": { "background": "var(--wp--preset-color-primary)", "text": "var(--wp--preset-color--contrast)" }, ":hover": { "color": { "background": "var(--wp--preset-color--contrast)", "text": "var(--wp--preset-color--base)" } }, ":focus": { "color": { "background": "var(--wp--preset-color--contrast)", "text": "var(--wp--preset-color--base)" } }, ":active": { "color": { "background": "var(--wp--preset-color-secondary)", "text": "var(--wp--preset-color--base)" } } }, "h1": { "typography": { } }, // ... "heading": { "typography": { "fontWeight": "400", "lineHeight": "1.4" } }, "link": { "color": { "text": "var(--wp--preset-color--contrast)" }, ":hover": { "typography": { "textDecoration": "none" } }, ":focus": { "typography": { "textDecoration": "underline dashed" } }, ":active": { "color": { "text": "var(--wp--preset-color-secondary)" }, "typography": { "textDecoration": "none" } }, "typography": { "textDecoration": "underline" } } }, // ... }, "templateParts": {} }

<code>{
  "version": 2,
  "settings": {},
  // etc.
  "styles": {
    // etc.
    "elements": {
        "button": { ... },
        "h1": { ... },
        "heading": { ... },
    },
  },
  "templateParts": {}
}</code>
Copy after login
Copy after login

{ "version": 2, // ... "styles": { // Global level style "elements": { }, // Block level style "blocks": { "core/search": { "elements": { "button": { "color": { "background": "var(--wp--preset-color--quaternary)", "text": "var(--wp--preset-color--base)" } } }, // ... } } } }

<code>
所有按钮都在全局级别(`styles.elements.button`)设置样式。

我们也可以在DevTools中确认这一点。请注意,名为`.wp-element-button`的类是选择器。相同的类也用于设置交互式状态。

同样,所有这些样式都在全局级别发生,来自`theme.json`。每当我们使用按钮时,它都将具有相同的背景,因为它们共享相同的选择器,并且没有其他样式规则覆盖它。

顺便说一句,WordPress 6.1添加了对使用`theme.json`中的伪类(包括`:hover`、`:focus`和`:active`)或全局样式UI设置某些元素(如按钮和链接)的交互式状态样式的支持。Automattic工程师Dave Smith在一个YouTube视频中演示了此功能。

我们可以在`theme.json`中(最好在子主题中,因为我们使用的是默认WordPress主题)或在站点编辑器中的全局样式设置中覆盖按钮的背景颜色(不需要子主题,因为它不需要代码更改)。

但是,按钮将同时更改。如果我们想在按钮是特定块的一部分时覆盖背景颜色怎么办?这就是块级样式发挥作用的地方。

#### 元素的块级样式

为了了解如何在块级别使用和自定义样式,让我们更改包含在搜索块中的按钮的背景颜色。请记住,有一个按钮块,但我们正在做的是在搜索块的块级别覆盖背景颜色。这样,我们只在那里应用新颜色,而不是将其全局应用于所有按钮。

为此,我们在`theme.json`的`styles.blocks`对象上定义样式。没错,如果我们在`styles.elements`上定义所有按钮的全局样式,我们可以在`styles.block`上定义按钮元素的块特定样式,这遵循类似的结构:
</code>
Copy after login

{ "version": 2, "styles": { // Global level style "elements": { }, // Block level style "blocks": { } } }

<code>
看到了吗?我在`styles.blocks.core/search.elements.button`上设置了背景和文本属性,并使用了WordPress中预设的两个CSS变量。

结果?搜索按钮现在是红色的(`--wp--preset--color--quaternary`),默认按钮块保留其亮绿色背景。

我们也可以在DevTools中看到更改。

如果我们想设置包含在其他块中的按钮的样式,也是如此。按钮只是一个例子,所以让我们再看一个。

### 示例:在每个级别设置标题样式

让我们用一个例子来巩固所有这些信息。这次,我们将:

- 全局设置所有标题的样式
- 设置所有二级标题元素的样式
- 设置查询循环块中二级标题元素的样式

首先,让我们从`theme.json`的基本结构开始:
</code>
Copy after login

{ "version": 2, "styles": { // Global level style "elements": { "heading": { "color": "var(--wp--preset-color--base)" }, }, // Block level style "blocks": { } } }

<code>
这为我们的全局和块级样式建立了轮廓。

#### 全局设置所有标题的样式

让我们将`headings`对象添加到我们的全局样式并应用一些样式:
</code>
Copy after login

{ "version": 2, "styles": { // Global level style "elements": { "heading": { "color": "var(--wp--preset-color--base)" }, "h2": { "color": "var(--wp--preset-color--primary)", "typography": { "fontSize": "clamp(2.625rem, calc(2.625rem ((1vw - 0.48rem) * 8.4135)), 3.25rem)" } } }, // Block level style "blocks": { } } }

<code>
这将所有标题的颜色设置为WordPress中的预设基本颜色。让我们在全局级别更改二级标题元素的颜色和字体大小:
</code>
Copy after login

{ "version": 2, "styles": { // Global level style "elements": { "heading": { "color": "var(--wp--preset-color--base)" }, "h2": { "color": "var(--wp--preset-color--primary)", "typography": { "fontSize": "clamp(2.625rem, calc(2.625rem ((1vw - 0.48rem) * 8.4135)), 3.25rem)" } } }, // Block level style "blocks": { "core/query": { "elements": { "h2": { "typography": { "fontSize": 3.25rem } } } } } } }

<code>
现在,所有二级标题元素都设置为主要预设颜色,并具有流体字体大小。但也许我们希望在将二级标题元素用于查询循环块时使用固定fontSize:
</code>
Copy after login

The above is the detailed content of Managing CSS Styles in a WordPress Block Theme. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template