I\'m trying to make a CSS selector that matches all links except the hovered one.
Naturally I though of using the ~
operator to catch around elements:
You cant do what you are explicitly after, without using JavaScript due to the way CSS selectors work based on DOM hierarchy and their limited potential for traversal.
However, given what I imagine you are trying to achieve, why not apply the hover to the parent element and exclude the currently hovered a
?
(and an alternative)
div:hover a:not(:hover){
color:red;
}
The following selector matches all links except a hovered link:
a[href]:not(:hover)
When no link is hovered, this matches all links, which logically satisfies the requirement.
Note that a
matches all a
elements, including <a name=...>...</a>
(outdated, but works) and <a>...</a>
(valid, mentioned in HTML5 specs). Using a[href]
restricts us to a
elements that have href
attribute, i.e. to links.
If you actually meant to ask for a selector that matches all links except a hovered link if there is a hovered link and no element otherwise, then there is no CSS solution (but there are JavaScript solutions).
Demo (with green and red color)
css
a {
color: #f00;
}
div {
display: inline-block;
}
#scope1:hover > a, #scope2:hover > a{
color : #0f0;
}
#scope1 a:hover, #scope2 a:hover {
color : #f00 ;
}