Welcome to this lesson where we explore creating block stylesheets without using the theme.json file.
With this lesson, you will:
- you will describe a block stylesheet, and
- create a custom block stylesheet.
What is a block style sheet and when would you use it?
You always have the choice to write your CSS within theme.json.
Here is an example of this being done for the WordPress core gallery block. However, block stylesheets are the solution if ever your CSS starts to get too lengthy.
Let’s now take a look at a couple of block themes found on the WordPress directory.
- The first theme is called Ronny and it was created by ThemeinWP.
- The second one is called Charity Vibes created by Iconic Themes.
You always have the choice of placing your CSS within style.css.
However for a large project, you may want to consider breaking out your stylesheets per block and then placing it into a folder such as assets. You can improve the site performance and also make your larger project a little easier to manage.
Within the Ronny theme, they chose to place their block stylesheets within ‘assets/styles’ and within Charity Vibes, they chose to place their stylesheets within ‘assets/css’ and a file called blocks.css.
So you can see that you do have choices for naming your files and the folder.
Create a custom block stylesheet
Let’s take a look now at creating custom block stylesheets.
There are some naming conventions to take note of.
The class name for a block stylesheet is .wp-block-{namespace}-{slug} and for core blocks you would use the class .wp-block-{slug} and the block stylesheet would be core-{slug}.css.
To register block stylesheets, you use the wp_enqueue_block_style function.
You’ll be passing the block name as the first parameter and an array of arguments as the second parameter. You can use functions.php to register your block stylesheet.
Here is an example of how you would do this for the WordPress core image block and this is the minimum required in order for your style to appear in line within the head area of your page.
add_action( 'init', 'themeslug_enqueue_block_styles' );
function themeslug_enqueue_block_styles() {
wp_enqueue_block_style( 'core/image', array(
'handle' => 'themeslug-block-image',
'src' => get_theme_file_uri( "assets/blocks/core-image.css" ),
'path' => get_theme_file_path( "assets/blocks/core-image.css" )
) );
}
Next steps
You can learn more about block style sheets by referring to the theme handbook available to you on WordPress.org.