2012-07-02 57 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知识永远不会令我惊叹! –