20. November 2018

Gutenberg Quick Tips – 01 Editor styles

If you want to include custom CSS styling in the Gutenberg backend you will need to enqueue a custom stylesheet. There are two possible ways to do that:

Enqueue block styles

If you need block based styles you want to just include the styling per block. You can do that via enqueue_block_editor_assets just for backend styles and enqueue_block_assets for both frontend and backend. These styles should however be clearly scoped and not influence other parts of Gutenberg. You will need to be very careful and have only nicely scoped CSS rules in those stylesheets as these styles leak outside the Gutenberg editor. For example setting body { display: none; } will lead to the whole backend being hidden.

Enqueue global styles

However in most cases you may want to include a global stylesheet as normally you will have some base styling for the page (Typography, etc). You could do that via enqueue_block_editor_assets as well. This will probably result in your styles being overwritten by some of Gutenberg’s styles as they will have a higher specificity so this is not a good idea.

The Gutenberg team created an alternative for such styles such that they will be properly scoped and will have a higher specificity and thus win over the core styles in the backend. The good old add_editor_styles function known from including styling to the TinyMCE will also work for Gutenberg. It will parse your CSS and add a higher specificity by adding a .editor-styles class at the front of every style rule.

Gutenberg scoped styles

For this method to work you will need to declare theme support for editor styles. This can be done with add_theme_support('editor-styles') .

If people like this kind of short tips I will do some more of them in the future. Drop me a line on twitter if you liked it.

https://twitter.com/revenwo