2014-12-29 28 views
2

如何匹配第一個div,除非第一個div是div.error選擇第一種不包括div.class

<div> 
      <div class="error"> 
       <p>Error 1.</p> 
       <p>Error 2.</p> 
      </div> 

      <div> <!--I want to tag this--> 
       Content 
      </div> 
      <div> 
       Content 
      </div> 
      <div> 
       Content 
      </div> 
     </div> 

我嘗試:

div > div:first-of-type:not(.error) {color:red} 

div > div[class]:not(.error):first-of-type {color:red} 

的div.error可能出現與否(取決於是否有錯誤或沒有),所以我不能使用類似nth-of-type(2)

+1

我不清楚自己想做的事,但它聽起來像JavaScript可以解決你的問題 –

+0

我想,以配合在div評論「我想標記這個」 – Arkana

回答

3

您可以使用兩個se講師。檢查演示,測試兩種情況:

div > div.error:first-of-type + div, 
 
div > div:not(.error):first-of-type { 
 
    color: red; 
 
}
<div> 
 
    <div class="error"> 
 
     <p>Error 1.</p> 
 
     <p>Error 2.</p> 
 
    </div> 
 
    <div><!-- Should match this-->Content</div> 
 
    <div>Content</div> 
 
    <div>Content</div> 
 
</div> 
 
<hr> 
 
<div> 
 
    <div><!-- Should match this -->Content</div> 
 
    <div>Content</div> 
 
    <div>Content</div> 
 
</div>

+0

您的代碼工程很好,但我有點與代碼混淆。爲什麼這個句子'div:not(.error):first-of-type'在沒有錯誤的情況下工作,而不是在什麼時候工作?它不應該在兩種情況下工作?我認爲這句話的意思是:「標記第一個不是'錯誤'的div」 – Arkana

+1

'div> div:not(.error):first-of-type'如果第一個div沒有class' error'。如果'div:first-of-type'確實有一個class error,這個規則不匹配,不適用。相反'div> div.error:first-of-type + div'工作,這意味着獲得類型爲div的第一個div與類error。 – dfsq

1

.main div:first-child:not(.error),.main div.error+div{color:red;}
<div class="main"> 
 
      <div class="error"> 
 
       <p>Error 1.</p> 
 
       <p>Error 2.</p> 
 
      </div> 
 

 
      <div> <!--I want to tag this--> 
 
       Content :: red 
 
      </div> 
 
      <div> 
 
       Content 
 
      </div> 
 
      <div> 
 
       Content 
 
      </div> 
 
     </div> 
 

 
<div class="main"> 
 
      
 

 
      <div> <!--I want to tag this--> 
 
       Content :: red 
 
      </div> 
 
      <div> 
 
       Content 
 
      </div> 
 
      <div> 
 
       Content 
 
      </div> 
 
     </div>

+0

請問,你能解釋一下'div:first-child:not(「。error」)'嗎?我正在嘗試你的代碼,但似乎沒有工作,如果沒有錯誤div ... – Arkana

+0

更新了演示... –