2

I want to select the first element of a parent matching a specific type; the css equivalent of $(parent).children()[0]. For example, h1 tags that are the first child of a parent:

<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

EDIT I am aware that there is no 'parent' selector.

Jakob Jingleheimer
  • 30,952
  • 27
  • 76
  • 126

1 Answers1

5

I'd suggest, if you want to match the first h1 of a parent element (in compliant browsers) using :first-of-type:

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

If, however, you want to style a h1 element only if it's the first child of its parent:

h1:first-child {
    /* CSS to style the h1 only if it's the first-child of its parent element */
}
David Thomas
  • 249,100
  • 51
  • 377
  • 410