Why can we never have ul element as the child of a p element? I made a web page with the following code
<p> some text
<ul>
<li>...</li>
<li>...</li>
.
.
.
</ul>
</p>
here, he ul element is a child of the p element. However, in all major browsers(Chrome, Firefor, IE)(all latest versions), it got interpreted as follows
<p> some text</p>
<ul>
<li>...</li>
<li>...</li>
.
.
.
</ul>
<p></p>
I checked it by right-clicking on the ul element(in chrome) and selecting the inspect element option. I saw it in chrome but the other 2 browsers also behaved in the same way(css selecter 'p ul' didnt work well).
Why is it so? Can anyone tell a general case in which such changes by the browser takes place?
It has always been a rule in HTML that a
p
element can contain only text and text-level markup, not a list for example. Therefore, browsers imply a closing</p>
tag when ap
element is open and a start tag for a block level element, like<ul>
, is encountered. In your example, the</p>
tag after</ul>
is homeless and normally ignored.Please check the HTML specification, which clearly states that putting lists in a paragraph element is forbidden, and also give some examples on what could be done:
<p>
can have only inline elements as childs and no block elements (see, e.g, at MDN).<ul>
on the other hand is a block level element (MDN)!The reason why browser interpret your code as you have seen lies in the HTML5 parsing spec. The spec lists an example very much like your own: whatwg link.
Another interesting related question might be this: HTML: Include, or exclude, optional closing tags?