Drupal 8: Custom styles in CKEditor

Blog Tags: Drupal 8

While working on development projects, you may sometimes find that custom styling is required for the Drupal CKEditor module. One such case may be when a user wants to apply a different style than the predefined styles in the WYSIWYG editor. In such scenarios, developers are required to create a custom CKEditor style.

To create a custom style in the CKEditor for your Drupal 8 website, you need to include Styles in the WYSIWYG editor.

1-1.pngDrag Styles from Available buttons to Active toolbar

Let’s take a scenario where a user requirement is that the list bullets should have the disc size of the headings that are inside that li.

Usually, the markup for such scenario in the default CKEditor will be:

<ul>

<li><h1>Heading 1</h1></li>

....

<li><h6>Heading 6</h6></li>

</ul>

And in the output, the disc size will take the global font size and not the heading size.

2.png

Not the desired output

To easily achieve the output we want, we can create a custom CKEditor style.

  • Navigate to admin/config/content/formats
  • Select your Text Format and edit it
  • In Available Buttons, drag Styles from the Available Buttons to the Active Toolbar
  • Once Styles is added to the Active Toolbar, in the CKEditor plugin settings > Styles dropdown, add your style configurations.

3.png

Configurations

eg.

li.h1|List Heading 1

li.h2|List Heading 2

li.h3|List Heading 3

  • Save the settings.
  • Add a block or a node and you will be able to see Styles option in the WYSIWYG buttons.
  • Add the new list and you will see the new markup.
  • The output of this will be:

<ul>

<li class="h1">Heading 1</li>

....

<li class="h3">Heading 3</li>

</ul>


Add the style for the li with heading classes, and you will get a disc size that is the same size as the heading.

4.pngOur desired result

For real-time behavior in the CKEditor as well, all you need to do is add the CKEditor stylesheet library in your theme info.yml file.

ckeditor_stylesheets:

-build/ckeditor.css

Then, in ckeditor.css, add the style for the real-time behavior as well.

li.h1 {font-size: 48px;}

li.h2 {font-size: 30px; font-weight: bold;}

li.h3 {font-size: 24px; font-weight: bold;}

 

5.pngHow to configure to get the desired output
 

6.png

Real-time behavior in CKEditor

Cool! So now you’ve created your first CKEditor custom style.

If you found this post helpful, or if you have any questions, do leave a comment below.

Lights On