Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting <div> inside <p> is adding an extra <p> [duplicate]

Tags:

html

From http://webdesign.about.com/od/htmltags/p/aadivtag.htm

In HTML 4, the DIV element cannot be inside another block-level element, like a P element. However, in HTML5 the DIV element can be found inside and can contain other flow content elements, like P and DIV.

I have something like this inside a form

<p> <label...> <input...> </p> 

but when Rails auto-generates an error_explanation div wrapping the input, the one paragraph turns into two, and I see this in Firebug:

<p> <label...> </p> <div...> <input...> </div> <p> </p> 

Also, if I just add a simple

<p> <div> test </div> </p> 

the same issue occurs (JSFiddle) and it gets rendered in the DOM as

<p> </p> <div> test </div> <p> </p> 

Why?

Update: I e-mailed the author of the article and she made the appropriate changes.

like image 930
Steve Avatar asked May 26 '12 05:05

Steve


People also ask

Can I put div inside P?

In HTML 4, the DIV element cannot be inside another block-level element, like a P element.

Can you have nested p tags?

You cannot nest P elements it is illegal. The P element represents a paragraph. It cannot contain block-level elements (including P itself).

How do you put a div in a paragraph?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!

Should ul be inside P?

The short answer is that ol elements are not legally allowed inside p elements.


1 Answers

From the fine specification:

p – paragraph

[...]

Permitted contents

Phrasing content

And what is this Phrasing content? Phrasing content:

Consists of phrasing elements intermixed with normal character data.

Normal character data is just that: unmarked up text. Phrasing elements are:

a or em or strong ... [a bunch of other elements none of which are div]

So, <p><div></div></p> is not valid HTML. Per the tag omission rules listed in the spec, the <p> tag is automatically closed by the <div> tag, which leaves the </p> tag without a matching <p>. The browser is well within its rights to attempt to correct it by adding an open <p> tag after the <div>:

<p></p><div></div><p></p> 

You can't put a <div> inside a <p> and get consistent results from various browsers. Provide the browsers with valid HTML and they will behave better.

You can put <div> inside a <div> though so if you replace your <p> with <div class="p"> and style it appropriately, you can get what you want.

Your reference at about.com disagrees with the specification at w3.org, your reference is misleading you.

like image 81
mu is too short Avatar answered Sep 16 '22 21:09

mu is too short