How can I put DIV in P?

前端 未结 6 1409
陌清茗
陌清茗 2020-11-29 08:41

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.

相关标签:
6条回答
  • 2020-11-29 08:52

    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>

    0 讨论(0)
  • 2020-11-29 08:55

    form the w3 site:

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

    0 讨论(0)
  • 2020-11-29 08:59

    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.

    0 讨论(0)
  • 2020-11-29 09:00

    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.

    0 讨论(0)
  • 2020-11-29 09:01

    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.

    0 讨论(0)
  • 2020-11-29 09:13

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

    <p>
      paragraph text
      <span style="display: block;">Span stuff</span>
    </p>
    
    0 讨论(0)
提交回复
热议问题