Gutenberg provides different APIs that helps developer supercharge/extend the existing functionalities, Today; we will cover Gutenberg styling API in this tutorial along with an example.
What is Gutenberg styling API?
Gutenberg styling API allows us to extend existing Gutenberg blocks with additional styles. It’s a simple API, but can be very useful in some cases.
Getting Started
In order to get started, use this starter template “CakeWP/gutenberg-extension-starter-template” for quickly creating Gutenberg-based plugins.
How does Gutenberg block styles API work?
Here’s a high-level explanation of how a block-style works in Gutenberg.
When a block style is selected, Gutenberg adds a new class (generated from the block style slug) on the block wrapper.
Selector: is-style-{slug}
Then, we can style the block with CSS scoping with the generated selector above.
How to create additional block styles for Gutenberg list block
Gutenberg core list block is very useful when you want to display bullet points in your post/page, But currently (at the time of this tutorial), there isn’t any variety of built-in list styles you can choose from. Therefore, As an example for Gutenberg block styling API, we’ll extend the Gutenberg core list block with the following additional styles:
Style 1: Heart
Style 2: Star
Style 3: Arrow
You can register a block style in Gutenberg using registerBlockStyle(blockSlug,
method.styles
)
Currently, A Gutenberg block style consists of the following 3 properties:
- name: Identifier name of the block style.
- label: Block Style label
- isDefault(optional): By adding this optional “isDefault” property, You can specify that this certain block style should be used when no custom class name is provided.
// src/index.js
wp.blocks.registerBlockStyle("core/list", [
{
name: "heart",
label: "Heart",
}
]);
You can also unregister the above style like this: wp.blocks.unregisterBlockStyle('core/list', 'heart')
The code above registers a new style “heart” for the core Gutenberg list block.
Currently, the style won’t do anything because we haven’t added any styling yet. In this case, the generated selector should be “is-style-heart” (because of the provided style slug).
Let’s now add some styles for this particular block style.
/** src/editor.scss **/
.is-style-heart {
list-style-type: "❤ ";
}
If you’re using our Gutenberg starter extension template. Add this same styling in src → style.scss, In order for styles to work on the front-end.
The style should now work as expected.
Let’s now add other remaining styles (“arrow” and “star“).
wp.blocks.registerBlockStyle("core/list", [
{
name: "heart",
label: "Heart",
},
{
name: "star",
label: "Star",
},
{
name: "arrow",
label: "Arrow",
}
]);
Adding styling.
.is-style-star {
list-style-type: "★ ";
}
.is-style-heart {
list-style-type: "❤ ";
}
.is-style-arrow {
list-style-type: "→ ";
}
Leave a Reply