2012-07-02 66 views
0

我正在使用一個可簡化爲以下示例的項目進行項目工作。你稱之爲CSS中使用的技術名稱是什麼?你在CSS中選擇基於其祖先的元素的技術是什麼?

<html> 
    <head> 
     <style type="text/css"> 
     #numberone #numbertwo #numberthree 
     { 
      color: red; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="numberone"> 
      <div id="numbertwo"> 
       <div id="numberthree"> 
        This is red 
       </div> 
      </div> 
     </div> 
     <div id="numberthree"> 
      This is not red 
     </div> 
    </body> 
</html> 
+3

如果這是您的真實代碼,您的標記無效。 ID值在文檔中必須是唯一的。 –

+0

你的問題不清楚。 – Simone

回答

4

我假設你是指使用descendant combinators目標具有特定的祖先結構的元素。從規格:

後代combinator是分隔兩個序列 簡單選擇器的空格。形式爲「AB」的選擇表示元素B 是一些祖先元素A.

我要修改你的CSS使用類選擇,而不是ID選擇的任意後代,因爲ID值在文檔中必須是唯一的。這個例子將選擇與類名numberthree是與類名numbertwo元素是與類名numberone元素的後代子孫元素:

.numberone .numbertwo .numberthree { 
    color: red; 
} 

雖然這個例子將選擇與類名numberthree所有元素不管他們的祖先:

.numberthree { 
    color: red; 
} 

所以給你的榜樣標記(再次,修改爲使用類),以下將適用:

<div class="numberone"> 
    <div class="numbertwo"> 
     <div class="numberthree"> 
      This is red for both snippets above 
     </div> 
    </div> 
</div> 
<div class="numberthree"> 
    This is only red for the second snippet above 
</div> 
+1

對一個模糊問題的好答案,聽起來像是對我的功課。 – Damien

+1

在後代組合子取得名字之前,整個選擇器過去被稱爲[上下文選擇器](http://www.w3.org/TR/CSS1/#contextual-selectors),在這裏你只選擇一個元素某些「背景」。這個術語在最近的規格中明顯缺失...... – BoltClock

+0

@BoltClock - 謝謝,我從來不知道這一點。你令人難以置信的CSS知識永遠不會令我驚歎! –