litel
litel

Reputation: 3980

Why doesn't ":focus:not(:active)" pseudo-class work?

I'm trying to figure out if there's a way to allow for prevent the styling of the ":focus" pseudo-class from being applying when there is a ":focus:active" or click event without the use of jQuery/JS. As the ":active" state is dependent on the ":focus" state, I would presume that ":focus:not(:active)" work, but it does not. Is there any way to combine ":not" with ":focus" to prevent "focus:active" from triggering "focus"?

Upvotes: 4

Views: 12578

Answers (4)

Joeri
Joeri

Reputation: 2308

Well... a:focus:not(:active) works.

A thing that is important and a bit of a gotya, is the order of rules.
Always place the active as last so it overrules the hover.

It might be you want it on a none focus element like div.
Then you would need to add a tabindex for the browser to be able to set focus on the div.

And a thing to notice is that you need to assign the rules to a class or a type. A simple :hover { will not work on the div.

<html>

<head>
    <style>
    * {
        outline: none;
    }

    a {
        text-decoration: none;
        display: inline-block;
        padding: 3px 8px;
    }

    div {
        display: inline-block;
    }

    .magic:focus:not(:active) {
        text-decoration: underline;
        border: 1px solid black;
        padding: 2px 7px;
    }

    .magic:hover {
        text-decoration: underline;
        color: green;
    }

    .magic:active {
        text-decoration: line-through;
        color: red;
    }

    </style>
</head>

<body>
    <a   tabindex="1" class="magic" href="#"> hello </a>
    <div tabindex="2" class="magic" > world </div>
</body>

</html>

Upvotes: 2

Joska Potin
Joska Potin

Reputation: 31

You can juste use :focus-visible this selector only triggers on focus not on active.

Upvotes: 3

Scott Paradis
Scott Paradis

Reputation: 1267

:not(:focus) is the closest you can get in CSS

Upvotes: 5

Arjun
Arjun

Reputation: 1355

Something can not get focused until it is active. So :focus:not(:active) is impossible. It can never be triggered.

Upvotes: -4

Related Questions