New Feature: A better way of handling Block Styling (CSS)

From the first version of Block Lab there have been a couple of ways of handling styling for your custom blocks. You could:

  • Add the styling to the block template file
  • Add the styling to the theme

These were both OK, but there were a couple of weaknesses.

If you added styling to the block template file, that snippet of CSS was loaded for every instance the block was added to the page. For example, if you added 3 custom Testimonial blocks to your page, the CSS would be included 3 times. Not great for performance.

Alternatively, if you added the styles to the theme you didn’t get your styling in the editor. This is because (typically) the theme stylesheet isn’t loaded in the WordPress admin.

Granted there were ways around these issues, but they weren’t a part of the “blocks made easy” ethos of Block Lab.

So we came up with a better solution.

Inside the /blocks folder in your theme, where you keep your block template files, you can now add a block-{block name}.css file.

your-theme/blocks/block-foo.php
your-theme/blocks/block-foo.css

As long as you follow the naming convention, Block Lab automatically recognises that this CSS file is paired with the related template file.

Here’s the really cool part though

  1. The CSS can now be loaded, by the plugin, to the WordPress admin so you get your styling in the editor without having to duplicate code, and
  2. The CSS is CONDITIONALLY loaded, only once, on the front end, and only if the relevant block is on the page

This new feature is a fantastic, yet super simple, solution to making conditional stylesheets accessible to even the most beginner WordPress dev.

We’re really excited about this feature and you can read more about it in the documentation.

Get the latest release of Block Lab from WordPress.org and give it a go.

Leave a Reply

Your email address will not be published. Required fields are marked *