【发布时间】:2011-07-14 07:44:55
【问题描述】:
选择某个类的第一个元素的语法是什么?请说明该选择方法是 CSS3 还是 CSS2.1 的一部分。
【问题讨论】:
标签: css css-selectors
选择某个类的第一个元素的语法是什么?请说明该选择方法是 CSS3 还是 CSS2.1 的一部分。
【问题讨论】:
标签: css css-selectors
如果您需要在其兄弟姐妹中具有某个类的第一个元素,您可以使用
.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+ 和所有其他。
【讨论】:
这个问题和解决方案一样糟糕。 IMO 你应该以编程方式给第一个元素一个.first{} 类。
【讨论】:
试试这个
.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' 只有红色。
【讨论】:
.test 的第一个p。
.test,但其他兄弟有,那么什么都不会被选中。
.class-name:first-of-type {
⋮ declarations
}
【讨论】:
:first-of-type 选择器适用于元素名称,而不是类名称:developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type