NathanBarley
NathanBarley

Reputation: 461

CSS focus psuedo class, only on keyboard (tabbed) focus

It's a basic question really, but I can't find an answer. My CSS looks like this;

a:focus, button:focus{outline:3px solid #000;}

What I want is for the focus to only apply when the user tabs to those elements using the keyboard.

This is exactly how it works in Chrome, but in FF and IE the outline shows when the user clicks on the elements. Which isn't what I want.

Is Chrome in fact wrong? I'm trying to keep it simple and avoid Javascript is possible. How can I get the outline to show only when the user tabs around the page?

Browsers are IE8+, FF and Chrome only.

Thanks for any help!

Upvotes: 3

Views: 4178

Answers (3)

Aaron Noel De Leon
Aaron Noel De Leon

Reputation: 1169

Use :focus-visible. It's currently a W3C proposal for styling keyboard-only focus using CSS. Until major browsers support it, you can use this robust polyfill.

/* Remove outline for non-keyboard :focus */
*:focus:not(.focus-visible) {
  outline: none;
}

/* Optional: Customize .focus-visible */
.focus-visible {
  outline-color: lightgreen;
}

I also wrote a more detailed post just in case you need more info.

Upvotes: 1

ConorLuddy
ConorLuddy

Reputation: 2307

I did this a different way elsewhere, and thought I'd add it in here as an alternative solution for anyone who stumbles across it:

/**
* If user hits tab key then we add a class to <html> that lets us use
* additional styling hints to show focus etc.
*/

function detectTabKey() {
    $(document).keydown(function(e) {
        if (e.keyCode === 9) {
            $('html').addClass('is-tab-user');
        }
    });
}

Upvotes: 0

NathanBarley
NathanBarley

Reputation: 461

Ok I know I said no JS if possible, but I don't wanna to spend any more time on this ... so for anyone interested this is what I did

$("a, button, select, input[type=submit], input[type=text]").keyup(function(){
    $(this).addClass("focusOutline");
}).blur(function(){
    $(this).removeClass("focusOutline");
});

Which does the job just fine. HTH someone sometime

Upvotes: 1

Related Questions