Search code examples
cssckeditor5

Add CSS class to empty paragraphs


Is there a way to add a css class name to empty paragraphs in ckeditor so I can target them with css?

Empty paragraphs in ckeditor are not really empty because they contain a br tag so I can not use :empty to target them.


Solution

  • ckeditor empty paragraph

    From what I can see, the good thing is that those <br> inside empty paragraphs have an attribute which makes them easy to target.

    In the future, you might use a pure CSS solution like this one.

    p:has(> br[data-cke-filler="true"]) {
        /* styles here */
    }
    

    For now, you either have to style the
    directly. Depending on what you're trying to accomplish, maybe applying css to the <br> would suffice.

    br[data-cke-filler="true"] {
        /* styles here */
    }
    

    And if you are able to run javascript in ckeditor. This can easely be done today.

    Examples : with jQuery

    $( "p:has(br[data-cke-filler="true"])" ).addClass( "MyEmptyParagraphsClass" );
    

    or

    $( "br[data-cke-filler="true"]" ).parent().addClass( "MyEmptyParagraphsClass" );
    

    Example : with Native Javascript

    var brs = Document.querySelectorAll("br[data-cke-filler="true"]");
    
    brs.forEach(function(br) {
      br.classList.add("MyEmptyParagraphsClass");
    });