CSS: Prevent parent element getting :active pseudoclass when child element is clicked

后端 未结 12 825
暖寄归人
暖寄归人 2021-01-07 16:19

JSFiddle

When you click the button, you see that :active pseudoclass is triggered for the parent div. Is ther

12条回答
  •  有刺的猬
    2021-01-07 17:09

    I don't think :has pseudo-class will ever be available in stylesheets. If browsers finally decide to implement it, it will probably be only for JS APIs like querySelector.

    However, I have much more hopes for :focus-within, which seems much simpler to implement.

    #parent:active:not(:focus-within) {
      background-color: red;
    }
    

    Of course, it will only prevent :active from being applied to #parent when clicking a focusable element like a button. You can make other elements focusable by adding tabindex = "-1"

    Sadly, :focus-within is not widely supported, but you can use a JS polyfill.

    #parent {
      border: 1px solid black;
      width: 300px;
      height: 300px;
    }
    #parent:active:not(.focus-within) {
      background-color: red;
    }
    
    

    Or me

    Github does not allow hotlinking, so the snippet above might not work unless you copy the polyfill to your server and use it.

提交回复
热议问题