选择具有某个类的第一个元素的语法是什么?请指定该选择方法是否是CSS3或CSS2.1的一部分。
答案 0 :(得分:45)
如果您需要第一个元素<兄弟中的某个类,您可以使用
.myclass {
/* styles of the first one */
}
.myclass ~ .myclass {
/* styles of the others (must cancel the styles of the first rule) */
}
请勿尝试仅使用.myclass:not(.myclass ~ .myclass)
在一个规则中执行此操作,因为:not()
只接受括号中的简单选择器,所以它不起作用。
如果您想要整个文档中的第一个.myclass
,则无法单独使用CSS。
发布的:nth-of-type()
或:nth-child()
方法是错误的,即使它们偶然碰巧与您在页面中所需的元素相匹配。
浏览器支持兄弟选择器(〜):IE7 +和所有其他。
答案 1 :(得分:0)
这个问题和解决方案一样糟糕。 IMO 你应该以编程方式给第一个元素一个 .first{}
类。
答案 2 :(得分:-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>
第一个div'test'只有红色。
答案 3 :(得分:-2)
.class-name:first-of-type {
⋮ declarations
}