skip to Main Content

I am struggling to understand the strange rendered browser output when I try to nest lists (<ul> or <ol>) in paragraphs (<p>).
It seems as if CSS exits the scope of the outer paragraph as soon as the list occurs.
And it also seems independent from the browser and appears in e.g. in Firefox and Vivaldi alike.
I have problems to design my style sheet because the behavior is so unexpected and beyond my understanding and reasoning.
Maybe, I can best explain it with the following example HTML code.

<p style="background-color:red">
  First line.
  <ul style=background-color:yellow>
    <li> Item one </li>
    <li> Item two </li>
  </ul>
  Last line.
</p>

This is how it looks like in the browser:

snapshot

I would expect that there is a yellow block inside a red block.
But instead, entering the list seems to leave the outer scope.
And the "Last line." is neither red nor yellow.

Can anybody point me to the inner logic of this behavior?

3

Answers


  1. Nested block-level elements like <ul> inside <p> can lead to unpredictable rendering due to HTML specifications; consider using <div> elements for desired styling.

    Login or Signup to reply.
  2. Paragraphs can only have phrasing content.

    p is an element that doesn’t require an explicit closing tag. As such, the tag is automatically closed once the browser hits a non-phrasing content element – such as your ul.

    So your browser actually renders your intended

    <p style="background-color:red">
      First line.
      <ul style=background-color:yellow>
        <li> Item one </li>
        <li> Item two </li>
      </ul>
      Last line.
    </p>
    

    as

    <p style="background-color:red">
      First line.</p>
    <ul style=background-color:yellow>
      <li> Item one </li>
      <li> Item two </li>
    </ul>
    Last line.
    <p></p>
    

    If you need to wrap your list in another element, use a div, a section, article or whatever most closely meets the semantics of your content at that point.

    Login or Signup to reply.
  3. You can use a div for that purpose instead of the p tag:

    <div style="background-color:red">
      First line.
      <ul style=background-color:yellow>
        <li> Item one </li>
        <li> Item two </li>
      </ul>
      Last line.
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search