Different css rules for TinyMCE and Gutenberg while using add_editor_style()

I wanted to include some CSS rules inside of my gutenberg editor (in a way that it better reflected the frontend of the website). Yet I absolutely didn't want to see the same styles applied inside of any Tinymce instance across the backend. I found a simple CSS solution, and I would like to share!

Answers 1


    Using css it's possible to use of the :not() selector to exclude Tinymce instances, e.g. body:not(.mce-content-body) {...}


    Let's assume we have declared theme support for editor styles and included an editor stylesheet somewhere in our theme (e.g functions.php) like this:

    add_theme_support( 'editor-styles' );
    add_editor_style( 'something/something/css/editor.css' );

    For the sake of this example I would like our gutenberg background to be black. Inside of editor.css we can declare:

    body { background-color: #000 }

    Now our gutenberg background is black, but the same applies to any Tinymce instance across our site. Luckily, Tinymce instances are wrapped inside of an iframe and have more or less the following markup:

    <body id="tinymce" class="mce-content-body acf_content post-type-page post-status-publish ...">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>

    Since the body tag has a few handy classes, we can go back to editor.css and change the previously declared body statement with:

    body:not(.mce-content-body) { background-color: #000 }

    Now my gutenberg editor background is back, while any instance of Tinymce retains the default background. In this example, the :not(X) selector applies the desired background color to any body tag, with exception of those with a .mce-contnet-body class. At this point we may even decide to be more specific and target .post-type-page to add styles only for our pages or .acf_content to only apply some rules to Tinymce instances created by the Advanced Custom Fields plugin.

    Furthermore if you are using Less/Scss you may be able to structure your website main stylesheet so that your "screen.scss" and "editor.scss" more or less share the same @imports and @includes, reducing duplicates and allowing for changes applied to one or more properties to be shared between "scren.css" and "editor.scss".

    Finally - sometimes changes made to your editor.css file may not show/appear in Tinymce up as the stylesheet is cached. While developing if this happens, you may find helpful to open up a tab leading to your editor.css file (e.g. "wp-content/themes/theme-name/assets/css/editor.css") and hit refresh.

Related Questions