It’s actually pretty typical for sites to use different styles for headings on blog posts than on, say, display pages that use sections. For example, the headings used in something like this would be completely inappropriate on the blog (the h2s are just huge):
Blogs also have unique needs, in particular for headings. They might need default spacing above them to visually separate them from other content, or different default colors, or whatever.
All of that means that we need a reliable way to inject context-specific styles into the Gutenberg editor. Styles that, for example, need to show up on both the frontend and backend of the site, but only when you’re editing a blog post.
And I couldn’t find a tutorial to show me how to do this, so I thought I’d put together a few notes.
The way that I go about styling the Gutenberg editor in general is something like this:
The above gist shows how to add backend-specific styles. These will all get the .editor-styles-wrapper prefix added to them, which is great – it means that you’ll be less likely to break the backend of your site with a style that applies to stuff it shouldn’t. This is how you should mostly go about setting your defaults for Gutenberg, since most of the time you don’t need to target the editor in a specific context (like when you’re editing a specific content type).
NOTE: please don’t embed your entire theme stylesheet like this. You should only be styling the bits that need to preview properly, so you don’t need, for example, header/footer styles or contextual styles.
So, that gets us a big chunk of the way there, but what happens if you want to add styles that only apply if you’re on a blog post? If you were to add a style for body.single-post h3, for example, that would get prefixed to .editor-styles-wrapper body.single-post h3. That’s not going to target anything.
So here’s how you do it:
With this approach, you can use some styles along these lines to accomplish your goal. Be very careful – this approach gives you more power, so don’t abuse that power and accidentally target things you don’t want to. Here’s some sample scss I used on a recent site to change how the headings look on the backend (corresponding styles are used on the frontend of the site as well, but that’s a separate file):
You’ll note that these styles are carefully tuned to not affect anything that we’re not comfortable affecting, while still targeting only headings that are on the single post editor.
Leave a Reply