1

How can I use CSS to find the first element of a given type?

I was trying:

a:first-of-type { }

and

a:nth-of-type(1) { }

But they were selecting child elements as well. I need to select only the first <a> tag in the entire page.

sinhayash
  • 2,693
  • 4
  • 19
  • 51
Rick Helston
  • 733
  • 3
  • 11
  • 20

2 Answers2

0

The general case is impossible to do in CSS. Only JS/jQuery'd allow it or a precise knowledge of the structure of your HTML in a given page.

Why?
An element has no way to know if, in a preceding sibling of one of its ancestors, there'd be a "preceding" a element. Because there isn't and there won't be a parent selector.

<body>
  <p>
    <a href="#"><!-- the one you'd want to select -->
  </p>
  <a href="#"><!-- this one knows he is the first of his type in the pool of direct descendant (children) of body
                   but no more can be achieved (in CSS) -->
</body>

In pure CSS, you can select each first type of element of their respective parent for a given level, like:

body > * > * > a:first-of-type { /* level 3, great-grandchildren of body */ }

and that sums pretty much all

FelipeAls
  • 21,711
  • 8
  • 54
  • 74
  • This has nothing to do with there not being a parent selector. Even if there was, you wouldn't be able to use it to determine an element's overall index. This is why jQuery came up with :eq(). – BoltClock Jun 29 '15 at 07:57
-1

a:first-child{
  // your styles.
}

Use above code with the main selector container Prefix to this class you want.

for suppose here you want first a tag with your entire HTML page then just write

body a:first-child{
      // your styles.
}
Himesh Aadeshara
  • 2,114
  • 16
  • 26