2010-05-18 39 views
38
<div id="main">  
    <p> one </p>  
    <p> two </p> 
    <p> three </p> 
    <p> four </p> 
    <p> five </p> 
<div> 

我不想在第一<p>One</p>如何跳過第一個孩子?

p {color:red} 

應用CSS我只需要相反的:first-child

回答

63

隨着the negation pseudo-class

p:not(:first-child) { color: red; } 

瀏覽器支持very strong現在,但替代品包括:

p { color: red; } 
p:first-child { color: black; } 

和:

* + p { color: red; } 
+1

對於第二種解決方案,我建議使用'p:first-child {color:inherit; }'而不是'p:first-child {color:black; }'所以它適用於任何預設的顏色。 – 2016-02-23 09:07:20

20

昆汀的:not()解決方案的現代瀏覽器的偉大工程:

p:not(:first-child) { color: red; } 

他對舊版瀏覽器的替代方案也很好,除了它爲第一個孩子使用重寫規則。這不是需要,但是...

您可以簡單地使用兄弟選擇器來應用與上面相同的規則,而無需覆蓋p:first-child。無論這些規則一會工夫:

兩個組合器在這裏工作相同;它們之間的細微差別僅適用於混合中有其他元素的情況。有關詳細信息,請參閱提供的鏈接。

2

您還可以使用 「波浪」(〜)運算符

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    p ~ p { 
     background:#ff0000; 
     } 
    </style> 
</head> 
<body> 

    <h1>This is a heading</h1> 
    <p>The first paragraph.</p> 
    <p>The second paragraph.</p> 
    <p>The third paragraph.</p> 
    <p>The fourth paragraph.</p> 


</body> 
</html> 

這裏是的jsfiddle演示http://jsfiddle.net/RpfLa/344/

難道在FF 17快速測試,鉻23,Safari瀏覽器5.1,IE9,IE1- 8 compaitbility模式

+2

效率不高,因爲第6個「P」匹配了5次。 – Rudie 2013-11-19 18:47:59

+0

這是好點... – MonteCristo 2013-11-28 12:17:14

5

作品每次,並不需要解開:

p + p { 
    /* do 15 special things */ 
} 

它需要P之前的每個P。不要以後設置屬性來撤消它。你應該只添加,如果你能幫助它,不要減去。

11

我認爲:nth-child()將做的伎倆。

p:nth-child(n+2){ 
    background-color:red; 
} 

這種風格的所有除第一p標籤,因爲它開始的第二個孩子。然後,您可以使用p:first-child單獨設置第一個p標籤。

相關問題