1

If I have

<span style='display:none'>
    <p>this is some stuff</p>
    <p>more stuff</p>
</span> 

my nested <p> tags are hidden as I would have expected. The moment I add a <p> as a parent

<p>Some stuff
    <span style='display:none'>
        <p>this is some stuff</p>
        <p>more stuff</p>
    </span>  
</p>

The nested <p> tags are no longer hidden. While I can change the <p> to a <div> to get it to work, I don't understand why the former fails.

The above is a boiled down version of my actual markup. Changing to a <div> means reworking a lot so I'd like to find a way to use the <p> (or at least understand the rationale).

Thanks in advance

Starscream1984
  • 3,072
  • 1
  • 19
  • 27
user1821052
  • 484
  • 5
  • 14
  • 3
    You can't put a

    inside another

    http://www.w3.org/TR/html5/dom.html#paragraph

    – Aguardientico Apr 11 '14 at 19:37
  • 2
    A `span` element can't contain a `p` element. You're seeing browsers trying to "correct" your code (closing the span before the p begins for instance) – FelipeAls Apr 11 '14 at 19:38
  • possibly duplicate of http://stackoverflow.com/questions/12015804/nesting-p-wont-work-while-nesting-div-will and some other similar questions – Ilya Streltsyn Apr 11 '14 at 19:52

3 Answers3

1

You can't nest <p> tags. And in HTML5 a <span> can't contain a <p>. Running your code through a validator would've told you this.

j08691
  • 204,283
  • 31
  • 260
  • 272
1

Here's what could try to interpret a browser:

<span style='display:none'>
    </span><p>this is some stuff</p>
    <p>more stuff</p>
</span><!-- invalid, no opening tag -->

and

<p>Some stuff
    <span style='display:none'>
        </span></p><p>this is some stuff</p>
        <p>more stuff</p>
    </span><!-- invalid, no opening tag -->
</p><!-- invalid, no opening tag -->

In HTML5, many elements don't need to be closed (if the browser can programmatically determine where it should close) so in first example, that's what is happening: closing the span before the p begins.
In the second example, as stated by others, a p can't contain another paragraph so browser will close the first one before the second one begins.

  • use an HTML validator. Any error may have consequences in browsers, and you don't know which ones/how for sure. Time is better spent validating pages than trying to correct in your code something that's due to your code ;)
  • Use 2 sibling paragraphs and/or a parent div
FelipeAls
  • 21,711
  • 8
  • 54
  • 74
0

First, p elements can't be nested. Any opening <p> tag after another opening <p> is threated by the browser as </p><p>, because end tag for p is optional. Also, span element can't contain p elements, so browser has to correct this markup as broken. Together these rules result in DOM tree where 2nd and following p elements are not children of span any more.

You should always respect content models of the elements to avoid this problem.

Ilya Streltsyn
  • 13,076
  • 2
  • 37
  • 57