I'm trying to select the first h1
inside a div
with a class called detail_container
. It works if h1
is the first element within this div
, but if it comes after this ul
it won't work.
<style type="text/css"> .detail_container h1:first-child { color:blue; } </style> </head> <body> <div class="detail_container"> <ul> <li></li> <li></li> </ul> <h1>First H1</h1> <h1>Second H1</h1> </div> </body> </html>
I was under the impression that the CSS I have will select the first h1
no matter where it is in this div
. How can I make it work?
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <! DOCTYPE> must be declared for IE8 and earlier versions. The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it's parent.
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.
The h1:first-child
selector means
Select the first child of its parent
if and only if it's anh1
element.
The :first-child
of the container here is the ul
, and as such cannot satisfy h1:first-child
.
There is CSS3's :first-of-type
for your case:
.detail_container h1:first-of-type { color: blue; }
But with browser compatibility woes and whatnot, you're better off giving the first h1
a class, then targeting that class:
.detail_container h1.first { color: blue; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With