2011-03-13 89 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

相關問題