Css :first-of-type selector – first child element of type

Css :first-of-type pseudo class apply to an element if it is first sibling among its parent’s direct child elements of same type. Here is an example.

css-first-of-type

:first-of-type basic example

<style type="text/css" media="screen">
.foo > p:first-of-type {
  background-color:lightgreen;
}
</style>
<div class="foo">
  <div>div1</div>
  <p>p1</p>
  <p>p2</p>
  <p>p3</p>
</div>
refresh

Few points to note:

  1. Here the :first-of-type pseudo class style applies to all p direct child elements of div of class foo.
  2. To apply style to all direct child and descendant p elements we could have used .foo p:first-of-type. See more info at CSS direct child vs any descendant selector.

:first-of-type – include nested child elements example

This example contains two p elements which fulfil first-of-type requirements.

<style type="text/css" media="screen">
.foo p:first-of-type {
  background-color:lightgreen;
}
</style>
<div class="foo">
  <p>p1</p>
  <p>p2</p>
  <div><p>in_div_p1</p><p>in_div_p2</p></div>
  <p>p3</p>
</div>
refresh

:first-of-type – exclude nested child elements example

This example contains two p elements which fulfil first-of-type requirements. But since we are using .foo > p, only direct p child elements are eligible for this style.

<style type="text/css" media="screen">
.foo > p:first-of-type {
  background-color:lightgreen;
}
</style>
<div class="foo">
  <p>p1</p>
  <p>p2</p>
  <p>p3</p>
  <div><p>in_div_p1</p><p>in_div_p2</p></div>
</div>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments