选择放在另一个元素之后但不是立即放置的第一个元素

Ste*_*611 3 css css-selectors

如何选择另一个元素(例如 h1)之后的第一个元素(例如 h2)但不一定紧跟在 之后
因此,元素+元素(例如 h1 + h2)不起作用,因为它选择了紧跟在元素之后的元素

<h1> Title1 </h1>
..... <--! many tags but h2 -->
<h2> h2 Title2 selected </h2>
..... <--! many tags but h1 and h2-->
<h2> h2 Title3 not selected </h2>
Run Code Online (Sandbox Code Playgroud)

Tem*_*fif 5

我认为您无法使用一个选择器来实现这一点,因此您可以尝试以下操作:

h1:first-of-type ~ h2 {
  color:red;
}
h1:first-of-type ~ h2 ~ h2 {
  color:initial; /*we reset the style for the others*/
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <h2>h2 Title3 not selected </h2>
  <h1> Title1 </h1>
  <p>text</p>
  <h2> h2 Title2 selected </h2>
  <h3>text</h3>
  <h2> h2 Title3 not selected </h2>
</div>
Run Code Online (Sandbox Code Playgroud)