<< See other exercices

Understand pseudo-classes with your mouse

Learn how the pseudo classes are triggered (active, hover, focus, focus-within...) and how to prevent them

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). (see more on MDN)

For example, :hover can be used to change a button's color when the user's pointer hovers over it.

In this section, you'll understand the difference between hover, active, focus and focus-within.

Every time a pseudo class in an Exercice block is triggered you'll see the name of the triggered state at the top of the html element like on the picture below:

1 - hover

Matches when a user moves the mouse pointer over an element

1. Move your mouse over this text and see the pseudo classhoverappears

2 - active

Matches when an item is being activated by the user. When you start click on a element with a mouse for example

1. Click on this text and keep the mouse pressed and you should see the pseudo class active appear

3 - focus

Matches when an item is being focused by the user. When you click on an element with the mouse.
Buttons and link can be focused by default. To allow other HTML elements to be focused, you should add the key tabindex="0" to it.

1. Click on one of these or this link and check they have the focus state
2. After clicking on a button or link, press the space bar --> you should see that element be outlined
3. Press the tab key, the focus will go to the next focusable element
4. Press the shift+tab key, the focus will go to the next focusable element
5. Note: During the click you should see the state focus & hover & active 👀
6. Note-bis: There is one focusable element that is not a button or a link, did you find it ?

4 - focus-within

Matches when an item is focused or any of its descendants are focused

1. Click on one of these or this link and check the line has the focus-within state

5 - Disable pseudo class events on an element

Sometimes you do not want an element to be affected by pseudo-class. In that case, you can disable all pointer-events on this element.

1. Between the elements , , is an element with all pointer-events disabled, did you find it?

6 - There are much more pseudo-class

In this page, we only covered 4 pseudo classes but there is much more pseudo classes to use.
Go to MDN - Pseudo classes to find out all the pseudo-classes available 🥳

🎉
If you enjoyed this tutorial, share it to other people !


Every week, I publish a new tutorial / section.
Follow me on twitter to be notified when a new section is out (every week)

If you have any question or suggestion, please reach out on twitter also 🤗