Skip to content

Instantly share code, notes, and snippets.

@emkis
Created May 2, 2022 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emkis/1e946d5adad98a5467074cb9496dbb9f to your computer and use it in GitHub Desktop.
Save emkis/1e946d5adad98a5467074cb9496dbb9f to your computer and use it in GitHub Desktop.
CCS Rules for applying focus on Keyboard only
.CoolButton {
/*  Your regular Button styles */
background: #000;
padding: 16px 32px;
border-radius: 8px;
color: #fff;
font-size: 16px;
font-weight: bold;
box-sizing: border-box;
border: 0;
margin: 0;
cursor: pointer;
/*
I'm removing the default outline because
I'm going to create my custom outline.
*/
outline: none;
}
.CoolButton:focus {
/*
Styles for focus (100% compatible).
These styles will be applied for all kinds of focus
as Mouse, Touch and Keyboard.
Probably this is not something you want, but it works.
You need these in order to have focus styles for browser
that don't support `:focus-visible`.
*/
box-shadow: 0px 0px 0px 3px orange, 0px 0px 2px 0;
}
.CoolButton:focus-visible {
/*
Styles for focus (not so compatible for now).
These styles will be applied when the user focus
with the Keyboard only.
This is great, and probably what you want to be applied
always, so add the same focus styles above.
This rules will be applied only if the browser
supports the `:focus-visible`.
*/
box-shadow: 0px 0px 0px 3px orange, 0px 0px 2px 0;
}
.CoolButton:focus:not(:focus-visible) {
/*
If the browser supports the `:focus-visible`,
you will still be applying the `:focus` rules for all
kinds of focus.
To remove that behavior, you need to undo all
the `:focus` styles. You need to remove it because
you want to have focus styles when the user
is focusing only with the keyboard.
This selector is a hacky way to check if the browser
supports the `:focus-visible`.
These styles will be applied when the element
was focused by Mouse and Touch, and on these cases
you don't want the focus styles.
*/
box-shadow: none;
}
.CoolButton {
/*  Your regular Button styles */
background: #000;
padding: 16px 32px;
border-radius: 8px;
color: #fff;
font-size: 16px;
font-weight: bold;
box-sizing: border-box;
border: 0;
margin: 0;
cursor: pointer;
/*
I'm removing the default outline because
I'm going to create my custom outline.
*/
outline: none;
}
.CoolButton:focus-visible {
/*
Styles for focus (not so compatible right now).
These styles will be applied when the user focus
with the Keyboard only.
This is great, and probably what you want, but to be
backwards compatible with browsers that don't support
this, you need the rules of the file below.
*/
box-shadow: 0px 0px 0px 3px orange, 0px 0px 2px 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment