If you’ve used the PHP templating method to add custom blocks to your website content (instead of the built-in Template Editor), you may wish to also add CSS to style your block.
In this article, we’ll explain where block-specific stylesheets and global stylesheets should be located and how they are loaded on the website.
Table of Contents:
Block-specific stylesheet
The best way to add CSS to a custom block is to create a block-specific stylesheet.
This stylesheet will be automatically loaded by Genesis Custom Blocks, but only when it’s needed (when the relevant block is on a page). This prevents block styles from being loaded on pages where the block is not being used.
The block’s slug (which is determined in the custom block’s properties) should be used in the stylesheet’s filename. The correct format to use is:
block-{block name}.css
And the stylesheet should be placed in one of the following locations:
{theme directory}/blocks/{block name}/block.css{theme directory}/blocks/css/block-{block name}.css{theme directory}/blocks/block-{block name}.css{theme directory}/blocks/{block name}/block.css
Global stylesheet
In addition to block-specific stylesheets, you can also create a global block stylesheet that will style all your custom blocks.
Genesis Custom Blocks will try to enqueue a global block stylesheet under one of the two following conditions:
- You are using the Gutenberg editor
- Any custom block is used on the page
Note: These styles won’t load if you are not using any custom blocks.
The global block stylesheet will be loaded if it exists in one of these places:
{theme directory}/blocks/blocks.css{theme directory}/blocks/css/blocks.css{child theme directory}/blocks/blocks.css{child theme directory}/blocks/css/blocks.css
If the global block stylesheet exists in multiple places, it will only be loaded the first time it’s found.
So if there’s a stylesheet located in {theme directory}/blocks/blocks.css AND in {theme directory}/blocks/css/blocks.css, the second stylesheet will be ignored.
Expected stylesheet path
Genesis Custom Blocks always looks for a stylesheet in a child theme first and any stylesheet located there will take precedence over those in a different location.
If a stylesheet is not found in a child theme, the plugin will look for one in the parent theme.
Also, the plugin will automatically detect a stylesheet and include it in the editor when previewing the block, as well as the frontend of your website if the block is included.
Always enqueuing the stylesheet in the editor is intentional so it’s available and ready in case a block is added to the page.
Block styles are expected to load in the following order:
Editor styles:
These stylesheets are only loaded in the editor.
blocks/{name}/preview.cssblocks/css/preview-{name}.cssblocks/preview-{name}.css
Frontend styles:
These stylesheets are loaded both in the editor and on the frontend of your website.
blocks/{name}/block.cssblocks/css/block-{name}.cssblocks/preview-{name}.css
