During development projects, there are occasions where custom styling becomes necessary for the Drupal CKEditor module. This need arises especially when users seek to implement styles beyond the predefined options available in the WYSIWYG editor. In such situations, developers are tasked with crafting a bespoke CKEditor style.
To implement a custom style within CKEditor for your Drupal 8 website, the inclusion of Styles in the WYSIWYG editor is imperative.
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 a 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.
Creating a Custom CKEditor Style in Drupal
To easily achieve the desired output, follow these steps:
- Navigate to admin/config/content/formats.
- Select your Text Format and edit it.
- In the "Available Buttons" section, drag "Styles" from the available buttons to the active toolbar.
- Once "Styles" is added to the active toolbar, go to the CKEditor plugin settings > Styles dropdown, and add your style 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.
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;}
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.