Developing CSS custom properties with theme.json for enhanced WordPress themes

WordPress theme developers can use a theme.json file to streamline a process that used to rely largely on PHP. However, you can still use your HTML, JavaScript, and PHP skills to build your themes — and CSS is no exception. In fact, you use CSS custom properties within theme.json. This can enhance the design stage and offer greater flexibility.

In this guide, we tackle CSS custom properties head-on to explore how they work alongside WordPress and theme.json. But before we get there, let’s summarize theme.json, full site editing (FSE), and how CSS fits into this new design approach.

How theme.json works with WordPress

The theme.json file first appeared in WordPress 5.8. It’s a revolutionary way to design WordPress themes, using JSON syntax to build a configuration file. WordPress reads this and applies the results without the need for much PHP, CSS, or JavaScript.

A code editor window showing the contents of a theme.json file for a WordPress theme. The JSON structure defines theme settings, including schema versions, patterns, and color settings. In the background, a scenic landscape with mountains, forests, and terraced fields is visible.
A theme.json file within a code editor.

The global settings and styles within FSE control various visual aspects of your theme. These can include typical color palettes and typography, but they can also include layout options and individual Block and element styles.

While FSE is intuitive, powerful, adaptable, and easy to use, theme.json can help bridge the gap between the end user and developer roles. Almost every option theme.json gives you is also visible within the Site Editor.

The WordPress Site Editor interface, showing the home page of a website on the right-hand side of the screen, while the black, left-hand sidebar gives options for navigation, styles, pages, templates, and patterns.
The main Site Editor interface within WordPress.

Using theme.json offers many advantages when building WordPress themes. There are a few reasons for this:

  • You have a central location for your theme’s design configuration, which makes it easier to manage and update.
  • There’s less obfuscation between the front-end experience, Site Editor, and a theme’s codebase.
  • Using theme.json offers compatibility with the future of WordPress development and design.
  • The built-in functionality of WordPress means you reduce the need for the user to apply custom CSS.

Let’s take a look at how theme.json relates to FSE’s global settings and styles.

A primer on FSE’s Global Settings and Styles

FSE represents a new era of WordPress theme development, and Global Settings and Styles are at the forefront. This allows users to customize almost every aspect of a site’s appearance through the Site Editor functionality.

The WordPress Site Editor showing the Styles panel's input fields in the right-hand sidebar. It lets you make adjustments to typography settings. The left-hand side shows a partial view of a blue-themed webpage.
The Styles panel within the WordPress Site Editor.

Here, you can adjust aspects of your theme’s layout with options that used to require CSS or a third-party page builder plugin. Modifying margins, padding, and borders are examples, but there are plenty more.

The WordPress Site Editor, showing the Layout customization panel. It lets you customize content dimensions, padding, and block spacing. The left-hand side of the screen shows a partial view of a blue-themed webpage.
Working with typical CSS elements like padding and margins within the Site Editor.

You can even enable or disable much of this functionality within theme.json (or a Block’s own block.json file). This supports UI customization alongside the overall site design.

However, the options at your disposal — while extensive — might not cover every need. This will be especially true if you build a theme from scratch. This is one job CSS custom properties can help solve.

Understanding CSS custom properties

In PHP, JavaScript, and almost every programming language, variables hold the values of various elements in your code. For instance, you can store values such as names, dates, and numbers and use them throughout your program.

CSS3 variables — or CSS custom properties as we call them throughout this post — are supported by most current browsers. Internet Explorer doesn’t support them, nor does Opera Mini. Still, the major players all do.

A compatibility chart for CSS Variables (Custom Properties) across different web browsers. The chart shows high global usage at 97.05 percent and indicates widespread support across major desktop and mobile browsers.
The Can I Use website shows the current support for CSS custom properties.

CSS custom properties let you store values to reuse throughout your stylesheet. It’s a powerful way to create more dynamic and flexible CSS. You can update multiple style rules by changing a single value.

The concept of CSS variables isn’t entirely new. Preprocessors such as Sass use similar functionality. For instance, take the following Sass:

$font-stack: Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color

This processes into typical CSS:

body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}

However, CSS custom properties take this directly to the browser. This offers some advantages:

  • Dynamic updates. Unlike most preprocessor variables, you can update CSS custom properties “on the fly” using JavaScript.
  • Cascading nature. Custom properties will follow the CSS cascade, which gives you greater flexibility and more context-aware styling.

Custom properties will also be more performant by reducing code redundancy. Smaller stylesheets mean faster loading times.

The syntax for CSS custom properties

As with typical preprocessor variables, the syntax for CSS custom properties is straightforward. It uses double hyphens rather than dollar signs to specify a property:

:root {
  --primary-color: #007bff;
}

From there, you use the var() function to assign those properties to elements:

.button {
  background-color: var(--primary-color);
}

Note that you can also assign custom properties using the @ property. However, as you’ll understand shortly, WordPress simplifies this whole process.

Where you can use CSS custom properties

Versatility is the order of the day when it comes to CSS custom properties. With WordPress and theme.jsonYou have a few ways to use them:

  • Presets: You can define color, font, and spacing presets.
  • Block styles: Individual Blocks can use custom properties for consistent styling.
  • Global styles:  Custom properties are invaluable for site-wide design.

You can create completely custom properties for whatever purpose you wish. Let’s look at a practical example of how you might use custom properties in your theme.json file:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "#007bff",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "line-height": {
        "body": 1.5,
        "heading": 1.2
      }
    }
  },
  "styles": {
    "typography": {
      "lineHeight": "var(--wp--custom--line-height--body)"
    },
    "blocks": {
      "core/heading": {
        "typography": {
          "lineHeight": "var(--wp--custom--line-height--heading)"
        }
      }
    }
  }
}

Here, we define a color preset and use the custom property to define line-height values for the pages headings and body. WordPress will generate CSS properties for the elements you define using custom. Further down, we can assign these custom properties to various styles, settings, Blocks, and more.

The benefits of using CSS custom properties

You may already have ideas about how CSS custom properties can help you when developing themes. Even so, there are plenty of benefits to note.

We already talk about modularity and reusability. All of the common values you define as custom properties will promote consistency and reduce redundancy. That redundancy will translate into better potential performance for your theme.

For the end user, custom properties provide several advantages:

  • Simplified customization. Users and site owners can customize a theme without the need for complex CSS knowledge. Once you expose variables through theme.json, users can access the settings through the Site Editor.
  • Better compatibility with FSE. Custom properties align with FSE principles, allowing you to create more flexible and dynamic theme designs.
  • Easier maintenance and updates. If you need to update common values across your theme, a custom property means changing it in just one place. It streamlines your maintenance and makes updates and tweaks more manageable.

Overall, custom properties can improve your theme development workflow. Determining them is also more straightforward than using typical CSS variables.

How to define CSS custom properties within theme.json

Let’s get into the practical aspects of defining and using CSS custom properties within theme.json. The first step is learning how to write them.

Syntax and naming conventions

WordPress offers the custom property to help with definitions. This is slightly easier to use than the @ property or definitions within pseudo classes, and uses the standard key/value format:

{
  "settings": {
    "custom": {
      "property-name": "value"
    }
  }
}

Behind the scenes, WordPress will process this definition and generate a CSS custom property using double hyphens:

--wp--custom--<custom-element>

--wp--custom-- will always be a part of your CSS property, and it won’t use camel case. For instance, if you define lineHeight as a custom property, WordPress will turn it into “kebab case:”

--wp--custom--line-height

When it comes to naming conventions, you can use camel case if you wish, although we advise kebab case for your custom property names. This is consistent with WordPress’s naming conventions, improves readability, and cuts down on processing errors.

Note: CSS custom properties use double hyphens because the W3C’s CSS Working Group also wants to encourage you to use Sass (which uses dollar signs to define properties). This way, you have the option of both to enhance your designs.

WordPress already defines some custom properties — or at least, themes have that option to do so. This means you’ll see CSS variables within theme.json without an explicit declaration:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "var(--wp--preset--color--primary)",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "spacing": {
        "small": "1rem",
        "medium": "2rem",
        "large": "3rem"
      }
    }
  },
  "styles": {
    "spacing": {
      "blockGap": "var(--wp--custom--spacing--medium)"
    }
  }
}

In this example, we define a primary color using an existing preset color. Then, we define some custom spacing properties and then set them using var().

This means we don’t need to hard-code values into theme.json. What’s more, users can update these values within the Site Editor and have them propagate throughout the theme.

Presets vs. custom properties

Of course, theme.json also lets you define presets for colors, font sizes, and other common theme elements. On the other hand, you can use custom properties for any value you want to reuse throughout your theme.

The biggest difference here is in naming conventions and accessibility. Users won’t be able to access custom properties in the Site Editor without further work on your end. With presets, WordPress will generate CSS that looks similar to how it processes custom properties:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "#007bff",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "fontFamily": {
        "base": "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif",
        "headings": "'Helvetica Neue', Helvetica, Arial, sans-serif"
      }
    }
  }
}

Once WordPress processes this, you can see the inherent differences:

--wp--preset--primary: #007bff;
--wp--custom--font-family--base: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
--wp--custom--font-family--headings: "'Helvetica Neue', Helvetica, Arial, sans-serif";

Notice that further property nesting will use double hyphens, even after converting camel case to kebab case.

Global and Block-specific CSS versus CSS custom properties

With classic WordPress, you would use additional and custom CSS on the front end to design elements within your theme. This is still the case with theme.json and FSE, although the approach is different from CSS custom properties.

If you visit the Site Editor and head into the Styles screen, you’ll spot the Additional CSS section. This acts much like a Custom CSS panel within classic WordPress installations:

A partial view of the WordPress Site Editor showing links to the Blocks and Additional CSS settings. The left-hand side of the screen displays a partial view of a building against a blue sky.
The Additional CSS section within the WordPress Site Editor.

This represents a way to add global CSS customization to a theme. However, it’s really a way to give users the ability to add CSS. You might also use this to make small, minor changes that don’t warrant a whole stylesheet.

Within theme.json, you use the css property to define any extra CSS you want to add:

{
  "version": 3,
    "styles": {
      "css": "margin: 0"
    }
}

Note that you don’t need to use semicolons to end CSS statements. You’re also able to set custom CSS for Blocks, too:

{
  "version": 2,
  "styles": {
    "blocks": {
      "core/post-title": {
        "css": "letter-spacing: 1px;"
      }
    }
  }
}

Any time you set CSS like this within theme.json, you will see it within any Site Editor Additional CSS fields. However, remember that nothing you declare using css is a CSS custom property.

Using the ampersand (&) selector

Much like Sass, WordPress also supports the ampersand selector, with a few differences. In this case, it’s a great way to target nested elements and properties. This could be relevant if you choose to declare CSS custom properties for individual Blocks.

For example, take the following:

…
"styles": {
  "blocks": {
    "core/table": {
      "css": "color:#333 & th{ background:#f5f5f5; }"
    }
…

This defines a text color and a background color to the table header element. Once WordPress processes it, you get clean, plain CSS:

.wp-block-table > table {
  color: #333;
}

.wp-block-table > table th {
  background: #f5f5f5;
}

Ampersand selectors are excellent if you wish to extend the CSS you target. An understandable way to think of the selector is that it helps separate your CSS elements. Take the following, for example:

{
  "version": 3,
  "styles": {
    "blocks": {
      "core/avatar": {
        "css": "& img {border-radius: 999px}"
      }
    }
  }
}

This adds a border radius to an avatar and outputs the CSS as you’d expect:

.wp-block-image img {
  border-radius: 999px;
}

However, without the ampersand, WordPress would conjoin your declarations:

…
​​.wp-block-imageimg
…

Using the ampersand selector for your CSS custom properties will be something you do on a regular basis.

Kinsta’s role in supporting modern WordPress development

Your choice of hosting is just as important as any coding language, preprocessor, or other technical element. Without a quality hosting provider at your side, you won’t be able to benefit from the performance and toolset of theme.json or FSE.

Kinsta can be central to your entire workflow, thanks to our development tools. You can start with DevKinsta — our local development environment that uses Docker containers to isolate your WordPress installation:

The DevKinsta interface showing the database and WordPress configuration settings. It displays connection details, including host, port, database name, and WordPress version. The interface also shows options to enable debugging and auto-updates for WordPress.
The main DevKinsta interface.

One useful piece of functionality is DevKinsta’s ability to push and pull data between your local machine and your Kinsta staging environments:

A partial view of the DevKinsta interface displaying site information and control options. The interface shows buttons for opening the site, syncing, accessing the database manager, and WordPress admin. A drop-down menu reveals options to push to or pull from Kinsta. The site type is listed as WordPress, with visible yet partial information about the host.
The options to push to or pull from Kinsta within DevKinsta.

This lets you test your themes in a production-like setting before you begin to distribute them. When working with CSS custom properties, you can ensure they work across different contexts. Kinsta’s API can support your CI/CD pipeline when you are ready to go live.

Other aspects of Kinsta’s architecture will help you across your entire development setup. For instance, Kinsta supports Git, which makes it easy to version control your theme files, including theme.json. For iterating custom properties, or simply experimenting with different configurations, you’ll want to know you have a rollback option.

Finally, if you choose to use your theme on a Kinsta server, our Edge Caching increases the performance of theme.json by up to 80 percent. Having a website that runs fast regardless of the user’s browser will make sure those custom additions display promptly.

Summary

Just as theme.json is a powerful configuration file for creating flexible and maintainable WordPress themes, CSS custom properties are crucial to the workflow. This is how you’ll build and declare CSS for elements the Site Editor doesn’t reach. It will also be key if you build your own Blocks or simply want to develop unique WordPress themes with the ultimate customization depth. What’s more, you also have the option to share that CSS with users through the Site Editor.

Will CSS custom properties be a part of your theme development workflow? If so, how will you use them? Share your insights in the comments section below!

The post Developing CSS custom properties with theme.json for enhanced WordPress themes appeared first on Kinsta®.

版权声明:
作者:Mr李
链接:https://www.techfm.club/p/158236.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>