Difference Between :last-of-type And :last-child
CSS
08/07/2021
Starting off with the simpler :last-of-type
pseudo-class, imagine this example.
<style> li:last-of-type { color: red; }</style>
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <!-- Red --></ul>
In plain English, this rule simply means: select and color red the last element of type li
inside a parent element. You can mix the group with as many other tags as you'd like and still get the same result.
<ul> <li>1</li> <li>2</li> <li>3</li> <p>Bus</p> <li>4</li> <!-- Red --> <p>Car</p></ul>
Gotcha
:last-child
is not as straightforward and can cause quite some confusion if not understood properly.
<style> li:last-child { color: red; }</style>
In plain English, this rule goes a bit differently: select and color red the last element of a parent if it's of type li
. As opposed to :last-of-type
, this pseudo-class actually contains a condition.
<ul> <li>1</li> <li>2</li> <li>3</li> <p>Bus</p> <li>4</li> <!-- Not red --> <p>Car</p></ul>
If you were to apply it to our last example, 4
would not be colored red. The reason is that the last element of our ul
parent is not of type li
, but of type p
.