P标签中不能包含块级元素

· 1 min read

Recently during code review, I noticed someone had included div and other block-level tags within P tags. This is incorrect, and this article systematically explains why.

P Tag Positioning

The HTML

element (or HTML Paragraph element) represents a paragraph of text. This element typically appears as a block of text separated from adjacent text, either by vertical whitespace or first-line indentation. Additionally, <p> is a block-level element.

Phrasing content defines text and the markup it contains. Some phrasing content constitutes a paragraph.

Quoted from MDN, according to the documentation, P tags allow phrasing content inside them. However, block-level elements are not permitted.

Block-Level Elements Within P Tags

Direct Inclusion in HTML

The browser doesn’t report an error, but the code is automatically corrected.

Source code as follows:

 <p>
          <div>
            hello world
          </div>
    </p>

After browser parsing, it becomes:

<p>
    </p><div>
      hello world
    </div>
<p></p>

Notes

  • This creates a risk of bugs, for example, if the CSS selector is p>div, it will fail
  • If P tags contain inline elements like span, a, etc., there’s no problem

DOM Creation with JavaScript

Note that if created with JavaScript, the browser does not “correct the problem” and will create the DOM elements as-is


<p id=""myPara"">
</p>

<script>
      document.getElementById('"myPara"').innerHTML = ` <div>
            hello world
          </div>`;
    </script>

React and Other Frameworks

SPAs are very popular nowadays, but these frameworks are still JavaScript, so P tags can contain block elements as shown above, but there will be error reporting

Final Thoughts

Although the issue isn’t severe, following best practices is important. Standardized HTML benefits SEO and helps developers avoid the problems mentioned above, so it’s better to be mindful of this.

References