H4
is not immediately preceded by the #p2
. You should use a more loose sibling selector ~
(general sibling combinator):
#p2 ~ h4
Specification
E + F
an F element immediately preceded by an E element
E ~ F
an F element preceded by an E element
Important
But as many others have suggested in comments (and invalidly in answers) your HTML isn't valid. You can't just nest elements that shouldn't be nested. Browsers will reformat it conforming to the specification. Paragraph element can only contain phrasing content.
Elements belonging to phrasing category are
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
and plain text (not only consisting of white spaces characters).
A few other elements belong to this category, but only if a specific condition is fulfilled:
, if it contains only phrasing content
, if it is a descendant of a element
, if it contains only phrasing content
, if it contains only phrasing content
, if the itemprop attribute is present
, if it contains only phrasing content
, if the itemprop attribute is present
Based on reformatted HTML by the browsers, both headings will get colored as they both become siblings to the #p2
paragraph and are both preceded by the same paragraph.