CSS选择具有特定类的第一个元素

Web*_*ner 14 css css-selectors css3

选择具有某个类的第一个元素的语法是什么?请指定该选择方法是否是CSS3或CSS2.1的一部分.

Lea*_*rou 48

如果您需要在其兄弟姐妹中使用某个类的第一个元素,您可以使用

.myclass {
    /* styles of the first one */
}

.myclass ~ .myclass {
    /* styles of the others (must cancel the styles of the first rule) */
}
Run Code Online (Sandbox Code Playgroud)

不要试图.myclass:not(.myclass ~ .myclass)仅在一个规则中使用它,它将无法工作,因为:not()只接受括号中的简单选择器.

如果你想要.myclass整个文档中的第一个,那么单独使用CSS是无法做到的.

:nth-of-type():nth-child()贴方法是错误的,即使他们不约而同正好匹配你的网页你想要的元素.

浏览器支持兄弟选择器(〜):IE7 +和所有其他.

  • +1尼斯技巧(尽管浏览器支持). (3认同)
  • 浏览器支持实际上比 CSS 结构伪类更好。编辑我的答案以包含它。 (2认同)

ngd*_*duc -1

尝试这个

.testparent .test:first-child {
    color: red;
}

<div class="testparent">
<div class="test">test</div>
<div class="test">test</div>
<div class="test">test</div>
</div>
Run Code Online (Sandbox Code Playgroud)

第一个 div 'test' 仅具有红色。