Why you can do :hover::after and not ::after:hover

Yesterday I explained Basic CSS Terms with a mildly interactive graphic. In the example I added the pseudo class selector :hover and the pseudo element ::after to the selector.

Today I want to explain why they are only working in one order.

Let's see what :hover::after does:

a:hover::after {
    content: '-->';

With the above selector we select every <a tag and on hover we style the ::after pseudo element. In this example we add --> as the content.

As the name (pseudo element) says ::after is an element, even though you can't see it in the DOM. So a:hover::after {} behaves like a:hover span {} for example. We select the last element in the selector chain and apply our CSS to it.

This is only working in this order. You can not do ::after:hover because you can't detect the hover over a pseudo element. That's probably because it's not a real element. It does not exist in the DOM. It's only available in the so called Shadow DOM.

You always add a pseudo element at the end of a selector chain.

This is the same for other pseudo class selectors like :focus and the pseudo element ::before.

Working with pseudo elements is a popular method these days and I hope this might help you some day.

I also created a CodePen to demonstrate it:

See the Pen :hover::after by Martin Wolf (@martinwolf) on CodePen.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.