Add Theme Styles to CKEditor WYSIWYG in Drupal

Adding the styles to the CKEditor to reflect how the content will look once published is a nice feature you can add to the editing experience in Drupal.

By default, CKEditor will use the user agent styles to style the WYSIWYG editor if you don't tell it otherwise. If you are setting up your own custom theme from a starter base theme, this will be true so the editing experience won't be that great, to put it mildly. Also, if you are using a theme from a theme shop or the site, you may need to do this. Just for example, on checking the Barrio Bootstrap theme I noticed that it doesn't style the editing experience.  

For your own site, this may not be a big issue but if you are setting the theme up for someone else then you will probably want to set the WYSIWYG to reflect the design on the front-end. This helps with the correct selection of headings and gives a better idea of what the piece of content will look like. So how do we do this?

How do I add the styles to the CKEditor?

This is a pretty easy thing to do once you know how. All you need to do is add the below snippet to your theme info YAML file and Bob's your uncle!

  - css/typography.css

Note that this topography.css file can also be included in the theme libraries YAML file in the global styling block which is fine. In theory, you could add a totally independent CSS file that duplicates the style rules that are used for various body elements that use the CKEditor and on a complex site this may in fact be the best option.

Restricting usage of headings and markup in the CKEditor

Not exactly related to the CKEditor styling but you may want to limit people from using h1 in the WYSIWYG, which you should, so you will probably want to edit your text formats too. By default, the basic HTML text format is set up to restrict h1 usage but if you have set up Media or allow other HTML markup you may have left the "Limit allowed HTML tags and correct faulty HTML" unchecked. You can edit the allowed tags on the text formats page for each text format that content editors can use. For more information on this check out the article on text formats in Drupal (coming soon). But to get an idea of how it works I wrote about how to allow media in the CKEditor in my Drupal 9 Media article or if you want to have a poke around  I have  added the Text formats and editor path below:
Manage > Configuration > Content authoring > Text formats and editors

That's about it for modifying your theme so it shows the correct styles in the WYSIWYG CKEditor. If you enjoyed this tip for Drupal and would like to receive more front-end and design goodness every week, sign up for the newsletter by providing your best email below. Thanks for reading and see you soon.