CSS选择器:父级的第一个子级

时间:2013-09-12 21:02:35

标签: css css-selectors

我想选择匹配特定类型的父元素的第一个元素;相当于$(parent).children()[0]的css。例如,h1标记是父项的第一个子项:

<div>
  <h1 id="foo"></h1>     // match
  <div></div>            // not match
  …
</div>
<section>
  <h1 id="bar"></h1>    // match
  <div></div>           // not match
  …
</section>
<div>
  <div id="baz"></div> // not match
  <h1 id="qux"></h1>   // not match
  …
</div>

jsfiddle

编辑我知道没有'父级'选择器。

1 个答案:

答案 0 :(得分:4)

我建议,如果您想使用h1匹配父元素的第一个 :first-of-type(在兼容的浏览器中):

h1:first-of-type {
    /* CSS to style the first h1 of its parent element */
}

但是,如果您希望仅在h1元素是其父元素的第一个子元素时设置其样式:

h1:first-child {
    /* CSS to style the h1 only if it's the first-child of its parent element */
}
相关问题