János
János

Reputation: 35128

How can I put DIV in P?

How can I put div in paragraph? I changed the display to inline, but the browser divide the base paragraph to two element, and div will not member of paragraph.

Upvotes: 30

Views: 40284

Answers (6)

Julian
Julian

Reputation: 1027

Make a span, set it's style to a block.

<p>
  paragraph text
  <span style="display: block;">Span stuff</span>
</p>

Upvotes: 6

form the w3 site:

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

Upvotes: 42

Alohci
Alohci

Reputation: 83125

For those who think that validation is decisive, there are in fact two ways to get a div inside a p.

One way is to use dom manipulation in script. For example

var theDiv = document.createElement("div");
theDiv.appendChild(document.createTextNode("inserted"));
var theP = document.getElementsByTagName("p")[0];
theP.insertBefore(theDiv, theP.firstChild); 

See it in action here: http://www.alohci.net/text/html/div-in-p-by-script.htm.ashx

The other way is to use XHTML and serve it with an XML content type. (No support in IE prior to IE9)

See that here : http://www.alohci.net/application/xhtml+xml/div-in-p-by-mime.htm.ashx

(Do note however, that while it is possible this way - it is still not valid.)


But You makes the vital point. Semantically, it's nonsense. You wouldn't put a block of something in the middle of a paragraph if you were writing text on to paper, so there should be no need to do it in HTML either.

Upvotes: 2

clairesuzy
clairesuzy

Reputation: 27674

no you cannot nest anything other than an inline element in a <p> if you want the code to validate

from the property def:

<!ELEMENT P - O (%inline;)* -- paragraph -->

I know it's hard to understand those recs at times, but the bit in brackets means the <p> can only contain inline elements

you can (and should) use a <span> inside a <p> and if required you could change it's CSS display property to block or inline-block and that would be perfectly valid, as CSS properties do not change the actual definitions of an element.. in your case it sounds like you need an inline element so just use a <span>

Upvotes: 20

You
You

Reputation: 23824

You cannot nest a <div> element inside a <p> element according to the HTML standard. Consider why you even want to do this; it should never be necessary. A <p> element can only, and logically should only contain inline elements and text.

Upvotes: 2

johnlemon
johnlemon

Reputation: 21509

Div is a block. Span is inline. Both of them are containers. You have to set display:inline for the div with css. Of course it won't pass validation so better use span ( inline ) to achieve the same thing.

Upvotes: 0

Related Questions