Combining :hover and :active in CSS


I was wondering if there is a shorter way for combining :hover and :active, e.g. to shorten the following rule:

#nav a:hover, #nav a:active { color: #333 }

This rule makes the links to have the specified color on hover (desktop use) and when they are tapped (mobile use).

I saw a mention of

#nav a:hover:active { color:#333 }

It works for active but not for hover.

Just for the sake of saving a couple more bytes if possible. I guess it is not possible but just wanted to ask and see if there’s anything I missed.

Thanks for any ideas.

Your second rule says that the active state is applied when the element is hovered at the same time (which will always be the case). When you combine the pseudo elements you only get one target criteria and not either/or.

Your first method is the only way to achieve what you want.

1 Like

Thanks Paul, I trust your insight so I will stop my search about this. Just thinking out loudly, it might be handy to have something like

#nav a:hover|active { color:#333 }

To cater for both hover OR active states for the specified element.

Yes css doesn’t really have logic triggers which is why pre-processors are popular among some :slight_smile:

You stole my thunder :stuck_out_tongue: .

Except when :active is triggered by pressing the enter key on the keyboard (where it is focus rather than hover that is the other state).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.