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

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

:last-of-type basic example

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

Few points to note:

  1. Here the :last-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:last-of-type. See more info at CSS direct child vs any descendant selector.

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

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

<style type="text/css" media="screen">
.foo p:last-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

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

This example contains two p elements which fulfil last-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:last-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