2014-11-20 56 views
0

我想了解爲什麼下面的示例不像預期的那樣工作。我有一個風格,選擇一般的兄弟姐妹,但我也有孩子,我不希望被選中,但偶爾是。這是解釋問題的最簡單的例子。 第一個div>div.h是後代,而~與它不匹配。第二個p>div.h顯然是後代,但~選擇器是否匹配它。我嘗試過Chrome,Safari和Firefox,都表現完全一樣。我肯定錯過了什麼。 p「特別」?CSS通用兄弟組合(即〜)

<html> 
    <head> 
    <style> 
     .anchor ~ .h { color: orange } 
     .anchor2 ~ .h { color: blue } 
    </style> 
    </head> 
    <body> 
    <div> 
     <div class="h">black 1</div> 
     <div class="h">black 2</div> 
     <p class="anchor">the anchor</p> 
     <div class="h">orange 1</div> 
     <div> 
     <div class="h">should be black</div> 
     </div> 
     <p> 
     <div class="h">why isn't this black</div> 
     </p> 
     <div class="h">orange 2</div> 
     <p class="anchor2">anchor2</p> 
     <div class="h">blue 1</div> 
     <div class="h">blue 2</div> 
    </div> 
    </body> 
</html> 

回答

2

<div> elements are not valid children of <p>.

您的瀏覽器糾正你的錯誤(把你的<div>並把它<p>,而不是在它裏面後),並通過這樣做,使得div.h.anchor兄弟姐妹:

enter image description here


現在,如果您使用內聯el對此語句在你的段落,瀏覽器不糾正你的標記,你會得到您預期的結果:

.anchor ~ .h { 
 
    color: orange 
 
} 
 
.anchor2 ~ .h { 
 
    color: blue 
 
}
<div> 
 
    <div class="h">black 1</div> 
 
    <div class="h">black 2</div> 
 
    <p class="anchor">the anchor</p> 
 
    <div class="h">orange 1</div> 
 
    <div> 
 
     <span class="h">should be black</span> 
 
    </div> 
 
    <p> 
 
     <span class="h">why isn't this black</span> 
 
    </p> 
 
    <div class="h">orange 2</div> 
 
    <p class="anchor2">anchor2</p> 
 
    <div class="h">blue 1</div> 
 
    <div class="h">blue 2</div> 
 
</div>

+0

好吧,我明白了,DIV實際上並不是p的孩子。我發現了以下官方說明[鏈接](http://www.w3.org/TR/html5/grouping-content.html#the-p-element)。 'span'是一個很好的解決方案。 – keithrel 2014-11-20 21:04:28