【问题标题】:Select first element which is placed after another element but not immediately选择放置在另一个元素之后但不是立即放置的第一个元素
【发布时间】:2022-03-31 05:47:52
【问题描述】:

如何在另一个元素(例如 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>

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    现在可以使用一个选择器:

    h1:first-of-type ~ h2:not(h1:first-of-type ~ h2 ~ h2) {
      color:red;
    }
    <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>

    旧答案

    我认为你不能用一个选择器来实现这一点,所以你可以试试下面的方法:

    h1:first-of-type ~ h2 {
      color:red;
    }
    h1:first-of-type ~ h2 ~ h2 {
      color:initial; /*we reset the style for the others*/
    }
    <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>

    【讨论】:

    • 感谢您的回答。你认为,可以用 CSS4 编写:h1:first-of-type ~ h2 :not (h1:first-of-type ~ h2 ~ h2) { color:red;}
    • @Stef1611 老实说,我不能告诉你是否可以这样做。我仍然不习惯将在第 4 级中引入的高级选择器
    • 我不知道您是否感兴趣,但是当您回答我时,我将这些信息发送给您。它适用于 CSS4,但您必须删除 :not. Everything is explained here :stackoverflow.com/questions/54115629/css4-selectors-and-browser 前后的空格
    • @Stef1611 哦,是的,当然,我认为这个空间是你复制过去的一个简单的错字,但是是的,空间需要被删除......但我的意思是,因为它仍然在草稿中,我们不能确定它是否会始终有效,因为规范可能会发生变化。很多时候,一些选择器曾经在草稿下工作,然后它们消失了。
    • 再次感谢您的第一个回答,因为我是 CSS 新手,这引发了我的好奇心(正如我在另一个问题中所写的那样)。我发现在迷你浏览器中使用最新版本的 CSS 非常有趣。我不知道只有三个引擎(chromium、webkit 和 firefox),它解释了我很多事情。而这仅仅是个开始。
    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多