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 <abbr>
, <audio>
, <b>
, <bdo>
, <br>
, <button>
, <canvas>
, <cite>
, <code>
, <command>
, <datalist>
, <dfn>
, <em>
, <embed>
, <i>
, <iframe>
, <img>
, <input>
, <kbd>
, <keygen>
, <label>
, <mark>
, <math>
, <meter>
, <noscript>
, <object>
, <output>
, <progress>
, <q>
, <ruby>
, <samp>
, <script>
, <select>
, <small>
, <span>
, <strong>
, <sub>
, <sup>
, <svg>
, <textarea>
, <time>
, <var>
, <video>
, <wbr>
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:
<a>
, if it contains only phrasing content
<area>
, if it is a descendant of a element
<del>
, if it contains only phrasing content
<ins>
, if it contains only phrasing content
<link>
, if the itemprop attribute is present
<map>
, if it contains only phrasing content
<meta>
, 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.