2011-03-13 88 views

回答

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

+0

恩,不,它匹配每个'.test'的第一个'p'。 – BoltClock 2011-03-13 04:03:44

+0

是的,我编辑它。看起来像'玉米的彼得'解决了另一种方式... – 2011-03-13 04:08:26

+1

如果第一个孩子没有'.test',但其他一些兄弟会做,那么没有选择。 – BoltClock 2011-03-13 04:08:37

42

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

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

+3

+1好戏(尽管有浏览器支持)。 – BoltClock 2011-03-13 23:54:11

+1

浏览器支持实际上比CSS结构伪类更好。编辑我的答案包括它。 – 2011-03-14 00:11:58

+0

哦,这很令人愉快。 – BoltClock 2011-03-14 00:14:59

-1
.class-name:first-of-type { 
    ⋮ declarations 
} 
+6

':first-of-type'选择符适用于元素名称,不适用于类名称:https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type – 2013-06-16 22:08:13

相关问题