Categories
Gutenberg Wordpress

Match editor style to front-end

If you create a theme for WordPress, you will probably want the front-end and the back-end (the editor) look alike in most cases. It’s not that hard if you know how to do it.

wp_enqueue_style

You could use the enqueue_block_editor_assets hook to add styles, using wp_enqueue_style. This is how the twentytwenty theme does it. It loads the file /assets/css/editor-style-block.css. The CSS rules in this stylesheet are already prefixed with .editor-styles-wrapper, so they applies to the editor, not the other panels and chrome of WordPress.

add_editor_style

Better is to add theme support for editor styles and use the function add_editor_style() to load styles in the editor. In this case the styles will be automatically prefixed with .editor-styles-wrapper, and body will change into .editor-styles-wrapper. This is very usefull, because you can use the same style declarations used on the front-end.

This code would go into functions.php.

PHP

The WordPress code reference seems to be out of date. The block editor handbook explains it better.

Using rems

One caveat is using rems. If you set a font-size on your root-element (the html element) to define the size of 1rem, and set the size of a heading for example as 2rem, then in the back-end the size of your heading is relative to the root element of the admin page, which may differ from your intended size.

This would mean you would have to change all sizes in your styles that use the rem unit. A solution would be to keep the rem its default size (16px in most browsers).

For an elaborate account of how to tweak your front-end styling to look best in the Gutenberg editor, see this post of Rich Tabor.