如何根据父级属性进行选择

时间:2012-02-22 17:34:54

标签: html css css3 css-selectors

有没有办法选择DOM的only_childn-th-child等?我知道有some_tag:only-child.some_class:only-child#some_id:only-child等选择器,但是根据本身的标记或属性(类,ID等)进行选择>。我想要的是根据的标签或属性进行选择。

例如,我可能想要选择only-child .some_class,这是下面标识为B的div,而不是only-child } .some_class,即A

<div>
  <div class="some_class" id="A">
    <div id="B">
    </div>
  </div>
</div>

4 个答案:

答案 0 :(得分:4)

如果您正在寻找.some_class的唯一子项,则需要使用组合子将类选择器和伪类分开。两个不同选择器组之间的父子关系和祖先关系总是用组合子(分别为child combinatordescendant combinator)表示。

鉴于您的HTML,您需要使用子组合器>将其限制为直接嵌套在.some_class中的唯一元素:

.some_class > :only-child

答案 1 :(得分:3)

如果您正在选择一个元素,那么您可以在父元素或元素本身上使用属性和第n个子选择器:

section div:nth-child(1) { /*
  any div that is a first child under the section
*/ }

.some_class > :nth-child(5) { /*
  any element that is the fifth immediate child of .some_class
*/ }

section[title] > :nth-child(5) { /*
  any element that is the fifth immediate child of a section tag
  where the section tag has a title attribute
*/ }

答案 2 :(得分:1)

您可以通过使用子选择器(&gt;)在父类型后面列出某个元素的子元素来选择它。例如,您可以使用.someclass > *:nth-child(N)找到包含某个类的元素的第n个子元素(任何类型),它将查找所有.someclass元素并查找nth-child(N)的任何元素

重要的是要注意你应该使用子选择器(&gt;)而不是后代选择器(只是一个空格)来确保它不会选择每个子元素的第n个子元素(及其子元素,和他们等。)。

请注意,旧版本的IE和其他一些浏览器不支持此类选择器。

答案 3 :(得分:0)

查看W3 on attribute selectors

E.g。

div[lang=nl] span { 
    color: red; 
}

这会使span颜色中的所有<div lang='nl' />标记变为红色。

我让a fiddle here看到了它的实际效果。