Search code examples
htmlcsscss-selectorspseudo-class

CSS :first-child and :first-of-type (example)


I'm still in the process of learning the difference between :first-child and :first-of-type pseudo classes using live examples.

I copied some HTML/CSS code from another website added it to: http://codepen.io/muygalan/pen/RroQNp.

Question: When I remove the following code from my CSS file:

#blog article:first-of-type {
background: green;
}

Why doesn't the text nested within the <article> tag turn red?

Isn't...

#blog article:first-child {
color: red;
}

...supposed to turn the text color red if the previous :first-of-type has been removed from the code?


Solution

  • Here's a great explanation on CSS Tricks. Basically, the first child of the #blog div is not an article element; it's a header element. :first-child will match an element if it's the first element in the parent container. :first-of-type will match an element if it's the first element of its type in the parent container regardless of whether or not there are other elements preceding it.