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

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


如果你需要兄弟姐妹中第一个具有某个类的元素,可以使用

.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 +和其他所有浏览器。


尝试这个

.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'只有红色。


.class-name:first-of-type {
  ⋮ declarations
}
链接地址: http://www.djcxy.com/p/22861.html

上一篇: CSS select first element with a certain class

下一篇: What is the difference between :first