3

As <span> is an inline element and <p> is a block element I cannot understand how nesting a <p> element inside a <span> element will result with a block element. Here is my example:

div {
  background-color: cyan;
  border: solid;
}

p {
  border: solid;
}
<div>
  <span><p>STACK OVERFLOW</p> </span>
  <span><p>STACK OVERFLOW</p></span>
  <span><p>STACK OVERFLOW</p></span>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Tal Rofe
  • 457
  • 12
  • 46
  • Types are not inherited, so when you nest a block element inside an inline one, they will remain as they were. So, your `span` is still inline, but `p` inside is not and thus it gives the impression you are getting. – Tomek Buszewski Jul 17 '18 at 10:12
  • @B001ᛦ: That question does not appear to address the CSS aspect of this one. – BoltClock Jul 17 '18 at 10:12
  • @BoltClock yea got it.. thx – B001ᛦ Jul 17 '18 at 10:14
  • a hint : add some style to the span and what is happening – Temani Afif Jul 17 '18 at 10:15
  • 1
    This is probably the most suitable duplicate I could find: https://stackoverflow.com/questions/27413095/block-a-inside-inline-li-behaviour (I answered [this](https://stackoverflow.com/questions/22290281/what-goes-wrong-when-a-displayinline-custom-element-contains-displayblock-elem) as well but the "custom element" in the title is a red herring and is unrelated to the issue.) – BoltClock Jul 17 '18 at 10:18

1 Answers1

4

You simply cannot nest a p element inside a span element. The span element's content model should be phrasing content, which excludes elements such as p and heading elements. Since the span element's end tag is not omissible (i.e. it is required), the p element's start tag does not implicitly close the span element, so you get a validation error. However, browsers try to recover from the error, and they still render the p element as a block element.

To avoid this type of error in the future, I recommend validating HTML code using the W3C's HTML Validator and consulting the consulting the HTML5 specification (or a similar reference) about content models.

Tsundoku
  • 2,455
  • 1
  • 19
  • 31
  • While this is true, this does not address why the elements are laid out the way they are. Swap the span and p such that the p becomes the parent, apply display: inline to the p and display: block to the span, and the resulting layout is identical. – BoltClock Jul 17 '18 at 10:21
  • 2
    On closer inspection I think I see how it *does* address the question - "why does putting a p in a span result in a block?" "The browser renders the p through error recovery even though a p may not legally appear in the context of a span." – BoltClock Jul 17 '18 at 10:28