linkedin github twitter

What are pseudo-classes?

Pseudo-classes are special states that elements can be in. The style of these elements can be changed via CSS when one of those pseudo-classes are active.

:link/:visited Anchor Element on :link on :visited Anchor Element on :hover and on :active on :link on :visited

Above is an example of the pseudo-classes active, link, hover and visited. Test them out yourself! The functions of these pseudo-classes are self explanatory by their names but the breakdown is written below:

These pseudo-classes can be applied to many different elements and are not limited to links and buttons. These classes in particular are great for making websites more interactive and let particular elements standout from the rest using CSS only!


This is the regular h2 element.

Above are the :before and :after pseudo-classes. These are attach additional content (along with their own style) to already existing elements. As the class names imply, they allow content to appear before and/or after the target element. These pseudo-classes are particularly useful by applying them to whole elements/classes/ids, reducing the need for repetition on html.

1
2
3
4
5
6
7
8
9
10

Above are the child pseudo-classes; :first-child, :last-child, :nth-child() and :nth-last-child(). Child classes can be used to style a particular element or elements in a parent via order they are positioned.

As the names suggest first-child and last-child select the first and last element respectively. The nth-child() and nth-last-child() pseudo-classes work similarly as the previous ones except with the addition of defining the number when the element appears. The above example uses :nth-child(3) to style the 3rd element and :nth-last-child(4) to style the 4th element from the end.

nth-child pseudo-classes have even more functionality by the possibility of applying a formula of selection or selecting odd/even occuring elements. Below are some examples of nth-child styling:

nth-child(odd):

1 Odd
2
3 Odd
4
5 Odd
6
7 Odd
8
9 Odd
10

nth-child(even):

1
2 Even
3
4 Even
5
6 Even
7
8 Even
9
10 Even

nth-child(3n) - every third element:

1
2
3
4
5
6
7
8
9
10

nth-child(3n+1) - every third element starting from 1:

1
2
3
4
5
6
7
8
9
10

This is by no means an exhaustive tutorial on pseudo-classes. There are many more available! These are perhaps the most widely used and are perfect to apply to your work and improve your CSS skills!

By Stewart