Nesting block level elements inside the <p> tag... right or wrong?

Is it syntactically and semantically correct to nest <div> or any other block level element inside the <p> tag. I am talking about HTML4 Transitional DTD.

If not then is it OK to instead use <span style="display: block"> instead?


Solution 1:

Syntactically, a div inside a p is invalid in all standards of HTML. Moreover, when using a conforming HTML parser, it is impossible to place a <div> element inside a <p> in the DOM because the opening <div> tag will automatically close the <p> element.

Semantically, the correct choice depends on the content that you are marking up. You will need to show at least a sample full paragraph and possibly the content surrounding it to be sure of providing sufficient information for the correct semantic mark-up to be determined.

However, given that both <div> and <span> are semantics free, and that CSS in no way can ever change that, if you are certain that the contents of the <p> tag truly form a paragraph, and that <span style="display: block"> gets you the presentational effect that you are seeking, then that is valid HTML and would be a wholly appropriate solution.

Solution 2:

No, a paragraph element may not contain other block elements.

Reference

A paragraph tag is intended for a block of text. If your elements is a part of the text (and not block elements), it would be semantically correct, otherwise not. A span tag with display:block is still a block element.

Solution 3:

It is syntactically incorrect, as you can see for yourself using the W3C markup validator.

Semantically and practically I would say it's "ok" in the sense that a) it is very natural, b) all browsers handle it correctly (indeed this is one of the easiest problems they have to face daily).

If your HTML is produced by user input (e.g. an HTML editor widget using which visitors can leave comments) then I 'd say simply let it be, even if it is "incorrect".

Otherwise, you could change the markup a bit. Personally I would go with

<div class="para">
    <div>Some content</div>
</div>

and give .para appropriate margins with CSS.

Solution 4:

FWIW: I had a paragraph bracketed by paragraph tags. Inside that I put a div with display:inline on the div. But it still treated the div as a block element and closed the paragraph, creating a new line with a paragraph spacing.

It appears that any block element inside paragraph tags forces the paragraph to close even if the block element is being displayed as inline in its CSS.