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:
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
Nested block-level elements like
<ul>
inside<p>
can lead to unpredictable rendering due to HTML specifications; consider using<div>
elements for desired styling.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 yourul
.So your browser actually renders your intended
as
If you need to wrap your list in another element, use a
div
, asection
,article
or whatever most closely meets the semantics of your content at that point.You can use a
div
for that purpose instead of thep
tag: