How to add custom styling to our blocks?
Note, this feature is used for including styling for individual blocks. To add the framework stylesheet and other global theme stylesheets into the block editor, use the Editor stylesheets Theme settings.
Sometimes our custom blocks need special CSS styling that is not covered by the framework styling or by the global theme stylesheet.
The best approach is to create a special CSS stylesheet that contains the block styling and to instruct WordPress to load it only if the block is displayed on the current page.
Create a new CSS file
To do that, create a new CSS file with all the required CSS styling. First, we create the folder blocks
that will contain our block assets. The name doesn’t have to be blocks
, of course.
Next, we create a new file in the Project panel by right-clicking on the blocks
folder:
We will name the file fancy.css
:
Then, drag fancy.css
to the page.
IMPORTANT: CSS rules should be scoped to the target block. The best way to do that is to add a class to the main block element and then use that class in CSS selectors.
Let’s go back to our About me block and add the class fancy-block
to its main <section>
element.
The right-click context menu or the CMD + L open up the Assign class dialog:
CSS rules use the class to scope the styling to the block. Here we will add a short decorative line below <h3>
:
Click on fancy.css
in the Project panel to open the file in the code editor:
We then include the CSS file with the Style setting on the Block action. The value is the relative url of the stylesheet, in relation to the project folder. In our case, blocks/fancy.css
.
The stylesheet will be included both in the editor and on the front-end.
Including a stylesheet only in the editor
Use Editor style setting to add a stylesheet that should be included only in the editor.
Both Style setting and Editor style setting can be defined.
Sharing the same CSS stylesheets between more blocks
A group of blocks can share the same stylesheet. Just add it to each block with the Style setting on their Block actions.
Pinegrow generates resource handles based on the stylesheet name, so that the stylesheet will be included only once, even if more blocks are using it.
Including the framework stylesheet in the Block editor
Our blocks usually rely on styling provided by the global theme stylesheet or framework stylesheet such as Bootstrap and Tailwind CSS. Without these styles block don’t show up correctly in the block editor. Use Theme settings to include theme stylesheets in the block editor.
Next steps
This completes the Create Your First Block guide.
Explore the rest of Blocks documentation and tutorials to learn more.