Categories
Gutenberg WordPress

Gutenberg CSS Setup: An Idea

Note: This blog post is specific to SCSS, but one could apply this to other dynamic CSS generation tools like PostCSS.

The problem

The WordPress Gutenberg block editor has been out now for over a year as of writing this post. The best part about it is that the author of the post gets a back-end experience which is pretty close to the front-end.

This is accomplished by bringing front-end styles into the block editor. This brings with it the following challenges:

  1. One needs to maintain two style sheets: One for the front-end and one for the editor
  2. The editor has its own markup and styles which might need to be overridden

The solution

The solution would be to bring the front-end CSS into the editor, and then bring in the editor-specific CSS to override it.

So one would have two CSS files for the same block.

The proposition

Both the front-end and back-end styles live within the same SCSS file. This solves the following problems:

  1. Prevents duplication of styles and avoids CSS bloat
  2. One can see both the front-end and back-end code in one file, making it easier to debug

Example

Lets look at an example of a “Hello World” block.

editor.scss :

$is-editor: true;

@import "theme";

theme.scss :

$is-editor: false !default;

@import "block/hello-world";

hello-world.scss :

.wp-block-hello-world {
	padding: 50px;

	@if ( false == $is-editor ) {
		background-color: #eee;
		color: #000;
	} @else {
		background-color: #000;
		color: #fff;
	}
}

Explanation:

The editor.scss file is used to generate the editor CSS and the theme.scss file is used to generate the theme. As you can see, the editor file has no styles, it just declares itself to be for the editor and imports the styles from the theme.

The theme SCSS does the heavy lifting. It declares itself as not being the editor and imports blocks.

The block file has all the CSS as usual, but with the additional condition @if ( $is-editor ). This way we can override any styles, or generate different CSS depending on the context.


Admittedly, there are many ways of doing this. Its about finding the one that works best within your workflow!

Leave a Reply

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