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

Viewed 139

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

3 Answers

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>

An empty inline-block element can also do the job:

p:empty:after {
  content: '';
  display:inline-block;
}

p {
  outline:1px solid red;
}
<p><br></p>
<p></p>

<div style="font-size:30px">
<p><br></p>
<p></p>
</div>

Or like below:

p:empty:after {
  content: ' ';
  white-space:pre;
}

p {
  outline:1px solid red;
}
<p><br></p>
<p></p>

<div style="font-size:30px">
<p><br></p>
<p></p>
</div>

You can give the <p> an explicit height and line-height like this:

p {
  height: 1em;
  line-height: 1em;
}

Working Example:

table, tr, th, td {
  border: 1px solid rgb(191, 191, 191);
}

p {
  height: 1em;
  line-height: 1em;
  text-align: center;
  border: 1px solid red;
}
<table>
  <thead>
  <th>Column 1</th>
  <th>Column 2</th>
  </thead>

  <tr>
    <td>
      <p></p>
      <p>Two</p>
      <p></p>
      <p>Four</p>
    </td>
    
    <td>
      <p><br></p>
      <p>Two</p>
      <p><br></p>
      <p>Four</p>
    </td>
  </tr>
</table>

Related