0

In my code, there are two P tag in there. And I gave them border. I think there are two lightblue block in my code beacuse there are two p tags. But if I run this code, There are Three Blocks in there. I want to know why. Please help. Thanks for reading.

p {
        margin: auto;
        text-align: center;
        background: lightblue;
        height: 70px;
        width: 200px;
        border: solid 1px black;
        line-height: 70px;
   }
<html>
    
      <head>
        <meta charset="utf-8" http-equiv="content-type">
        <style media="screen">
          p {
            margin: auto;
            text-align: center;
            background: lightblue;
            height: 70px;
            width: 200px;
            border: solid 1px black;
            line-height: 70px;
          }
    
        </style>
      </head>
    
      <body>
        <p><p>dddddddddddoo</p></p>
      </body>
    
</html>

2
  • You can't nest a <p> inside a <p>, invalid HTML will cause you problems.
    – DBS
    Nov 18, 2016 at 15:55
  • If I am not wrong its because you can't put a p inside another p. So UA is probably putting one close </p> after the first opening <p> and one opening <p> before the last closing </p>. So you get three.
    – Harry
    Nov 18, 2016 at 15:55

4 Answers 4

6

Use your browser's element inspector to look at the actual DOM. The result is:

<p></p>
<p>dddddddddddoo</p>
<p></p>

A p within a p is invalid. When the browser encounters the second <p>, it implicitly closes the first p. Somewhere along the line a third p is being implicitly created from your invalid markup.

1

You can't nest a <p> inside a another <p> tag. This is invalid HTML. When HTML sees something like this,

It replaces your html with:-

 <p> </p>
 <p>dddddddddddoo<p>
 <p></p>
0

replace

<body>
    <p><p>dddddddddddoo</p></p>
</body>

with

<body>
    <p></p>
    <p>dddddddddddoo</p>
</body>
0

You can't nest <p> elements. The <p> element represents a paragraph. It can't contain block-level elements (including <p> itself). If you inspect it in your browser, you will see 3 paragraphs.

<div> however is a generic container where content can be inline e.g <span> or block-level. Hence <div> can contain <p> but not the other-way around.

See the updated fiddle: https://jsfiddle.net/862afpo5/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.