Register block styles in WordPress Gutenberg blocks

Add a named block style, then make its CSS available in both the editor and the frontend.

Adding custom styles to Gutenberg blocks is easy and at the same time very useful. All you need to do is to add a snippet in your functions.php or plugin file. Selecting a style to a block simply adds a class that you can style wherever you want!


Adding a style to a block with php

Below is a code example that adds a style named ‘my-cover‘ to the cover block. This adds a class called ‘is-style-my-cover‘ to the block.

add_action('init', function() {
	register_block_style('core/cover', [
		'name' => 'my-cover',
		'label' => __('My custom cover', 'mydomain'),
	]);
});

Style it in your stylesheet:

.is-style-my-cover { 
  background-color: pink;
  min-height: 80vh;
}

Add your styling to an admin stylesheet

In order to see your block styling in the editor, the WordPress editor also needs to read your css. Write a custom style sheet with the same styles (do this with scss & imports if you can!). Append the stylesheet to admin like this:

add_action('enqueue_block_assets', function () {
    wp_enqueue_style('my-block-styles',
        get_stylesheet_directory_uri() . '/css/my-custom-block-styles.css', []);
});

A registered stylesheet still needs to be loaded. Either enqueue it with enqueue_block_assets, or associate the registered handle with the style using style_handle, as below.

add_action('init', function () {
    wp_register_style('my-block-styles',
        get_stylesheet_directory_uri() . '/css/my-custom-block-styles.css', []);
    register_block_style('core/cover', [
        'name' => 'my-cover', 'label' => __('My custom cover', 'mydomain'),
        'style_handle' => 'my-block-styles',
    ]);
});

The style will show up here, along the WordPress default style:


Style variation or block variation?

A block style changes presentation through an is-style-* class. It does not create a new block type or change the query. Consult the register_block_style reference for supported arguments.

Good things, occasionally.

Fresh ideas, useful tools and better ways to build. Delivered when we have something worth sharing.