1

I've noticed a strange behaviour in how the browsers interpret the following code:

  <h2>Maecenas aliquet lorem id urna vehicula</h2>
  <p>&nbsp;
    <ul class="liststyle">
      <li>Curabitur</li>
      <li>Pharetra</li>
      <li>Convallis</li>
    </ul>
  </p>

When I tried to give this some style I tried the following selector:

p li {
  font-family: Verdana, sans-serif;
  font-size: 14px;
}

I know that a better choice is "ul li" but my selector (p li) should work and it doesn't, so looking the developer tools in Chrome and Firefox this is how they interpret the code:

<p>
</p>
<ul class="liststyle">
    <li>Curabitur</li>
    <li>Pharetra</li>
    <li>Convallis</li>
</ul>
<p></p>

The only difference is that Chrome also shows the entity (&nbsp;) that I put there trying to fix the problem, but still creates two paragraphs. I'm looking for an explanation of this phenomena. Thanks.

Alcides
  • 508
  • 1
  • 7
  • 15

2 Answers2

7

Paragraphs may not contain block-level elements. Some browsers apparently assume you've made a mistake and attempt to correct it.

Read more

Community
  • 1
  • 1
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 1
    Presumably because the closing-tag of a `

    ` element is optional; so when the browser encounters an element that shouldn't be contained within a `

    ` it automatically closes the paragraph. As for the second paragraph, that seems the more mysterious part, but seems to be a compensation for encountering a closing `

    ` without a corresponding `

    `.

    – David Thomas Mar 24 '15 at 15:13
  • 1
    Not some of the browsers, but all browsers must cope with invalid html code in order to parse it. They way they do it is not strictly defined and it is called [browser error tolerance](http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/#Browsers_error_tolerance). – skobaljic Mar 24 '15 at 15:13
4

Your issue is that the <p> tag shouldn't have block elements inside it according to web standards.

http://www.w3.org/TR/html401/struct/text.html#h-9.3.1

jdu
  • 581
  • 2
  • 3