Discover in this tutorial how to add custom CSS to a WordPress block using the theme.json file.
The theme.json file allows such a degree of customization of a WordPress theme that it’s worth getting familiar with it.
That’s why I’m publishing a set of tutorials focused on getting you to understand how it works and, more importantly, how you can customize it to your liking.
Starting with WordPress 6.2, the ability to add custom CSS directly from the theme.json file was added.
So in this tutorial we are going to see how you can do it.
Instructions for adding custom CSS to a block in a WordPress theme
1. Modify (or create) the theme.json file
In case your theme already has a theme.json file, look for the "styles"
section (if it doesn’t exist, create it at the same level as "settings"
) and add the following.
To see this and another 965 code snippets of this website, login or subscribe here.
In this simple example you are adding the CSS to the button block, so that the background is black.
In case your theme doesn’t have one, you have to create a file called theme.json and place it in the root of your theme. I recommend you to take a look at the tutorial where I explain the anatomy of the theme.json file.
Once you have done that, add the following code:
To see this and another 965 code snippets of this website, login or subscribe here.
2. Interface in the block editor
Once you have added this snippet, either by adding a new theme.json file or modifying an existing one, you will see that the code is displayed in the block advanced settings (in the global styles section).
Conclusions
Now you know how to add custom CSS to any block in a WordPress theme using the theme.json file.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂