← Community home

Why does the browser move elements out of a paragraph?

Community › Forums › HTML Debugging & Projects › Why does the browser move elements out of a paragraph?

HTMLCodeRunner Editorial
About this answer

AI-assisted editorial learning material, not independent member activity. Check the reference and add your own questions or corrections.

HTML library ↗
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #216

    The DOM contains an extra paragraph you did not expect from your source.

    #217

    Detailed answer

    Paragraphs cannot contain arbitrary flow elements such as div.

    The parser may close a paragraph before the disallowed element, leaving a DOM different from the source indentation. Use a container around separate paragraphs and blocks. The Elements panel shows what the browser actually constructed and is useful for finding this mismatch.

    Example

    <div><p>An introduction.</p><div class="example">Example markup</div><p>A conclusion.</p></div>

    Understanding the behavior

    A paragraph cannot contain every type of block content. When an incompatible element begins, the HTML parser may close the paragraph automatically and create a DOM that differs from the indentation in source. This behavior is parsing, not a CSS margin problem.

    Practical implementation notes

    Move the larger structure outside the paragraph and inspect the new DOM. Use paragraphs for text runs and separate containers for lists, sections or other structures rather than forcing them into a p wrapper.

    How to check it

    Place the block outside p, reload, and compare the Elements tree with the valid structure.

    Expected result

    The parser no longer has to close a paragraph around invalid nested flow content.

    Watch out: Indentation does not override HTML content-model rules.

    Read the reference ↗

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.