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.
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.
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
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.
}