Selecting all links except hovered one CSS only

后端 未结 3 1736
轮回少年
轮回少年 2021-01-22 14:15

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:



        
相关标签:
3条回答
  • 2021-01-22 14:39

    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?

    Demo Fiddle

    (and an alternative)

    div:hover a:not(:hover){
        color:red;
    }
    
    0 讨论(0)
  • 2021-01-22 14:55

    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).

    0 讨论(0)
  • 2021-01-22 14:57

    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 ; 
    }
    
    0 讨论(0)
提交回复
热议问题