Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the HTML paragraph <P> behaves so oddly on my chrome?

Tags:

html

Get an empty HTML, type in this and see its source code on Google Chrome:

<p><div>&nbsp;</div>WHY?</p>

If you did it like I did, you'll see this in the source:

<html>
<head></head><body><p>&nbsp;</p><div>&nbsp;</div>WHY?<p></p>
</body></html>

Just in case, here's a demo using jsbin. In that link, you see this:

[repeating P]


WHY?
[repeating P]

I've added this jQuery on it:

$("p").html("[repeating P]");

Remove the whole <div> from it, and everything goes back to normal. This small weird unexpected behavior is consistent when adding more things in the <div>, and it could be a <span> or I guess whatever in there. And it doesn't matter if the HTML is well formated or not.

Anyone knows why?

like image 796
cregox Avatar asked Mar 03 '11 21:03

cregox


People also ask

What does the P display on Web pages?

The <p> tag defines a paragraph. Browsers automatically add a single blank line before and after each <p> element.

Should I close P tag?

Technically this is optional, but it's good practice to include the closing tag to ensure your document validates. By default, most browsers place a line break and a blank line between paragraphs.


1 Answers

As a basic explanation, div is meant to be a 'box' for layout. A box for holding other things. The p element, however, is meant to be for (surprise) a paragraph of text.

Because a div (container) was put inside a p (inline element), it is (technically) incorrect. Google Chrome (being the standards-slightly-obsessed) browser that it is, it tries to correct this incorrect nesting by adding the extra elements as shown.

The W3C has a (very long) article about these language specifications on their site, however possibly the best thing to do to check for inconsistencies and potential problems like this is to Validate your written source code. The easiest way to do this is with the W3C Validator.

like image 138
nchpmn Avatar answered Sep 20 '22 19:09

nchpmn