Search code examples
htmlcssline-breaks

How to use css to implement same effect as having a <br> inside target element?


I want all empty <p> elements in html to have a line break inside it, and use css to make this effect.

Details:

Both of the p tags below should have same appearance (across browsers and zoom levels)

All other customs styles of p tags are same

p:empty {
  /** How can I code here (or some other way css codes can achieve this) **/
}
<p><br></p>
<p></p>

background: I want to show preview of the editing content inside prosemirror editor, while the editor doesn't preserve <br> inside <p> when serialize the content to json and make it look different when preview rendered from json. see: discuss.prosemirror


Solution

  • There's several ways you could do this, here's how you could it using the same logic behind your own code by simply adding a space Unicode after it's content :

    p:empty:after {
      content: '\00a0';
    }
    
    p {
      outline: 1px solid red;
    }
    <p><br></p>
    <p></p>

    To demonstrate :

    console.log(document.getElementById("first").offsetHeight)
    console.log(document.getElementById("second").offsetHeight)
    p:empty:after {
      content: '\00a0';
    }
    p {
      outline: 1px solid red;
    }
    <p id="first"><br></p>
    <p id="second"></p>