To add or change the outline color of HTML elements when focused using the tab key, you can use the :focus-visible
pseudo-class for the particular HTML element and then use the outline
CSS property and set its value of your choice.
TL;DR
<html>
<style>
/*
Using the `a` selector and using the `:focus-visible` pseudo-class
to change the outline style of the anchor tag when focused using the tab key
*/
a:focus-visible {
outline: 3px solid red;
}
</style>
<!-- A simple webpage with 3 anchor tags -->
<body>
<a href="#">Home</a>
<a href="#">About Us</a>
<a href="#">Privacy Policy</a>
</body>
</html>
For example, let's say have some anchor (a
) HTML elements for the navigation in the webpage like this,
<html>
<body>
<a href="#">Home</a>
<a href="#">About Us</a>
<a href="#">Privacy Policy</a>
</body>
</html>
A visual representation of the focusing the anchor HTML element tag using the tab key in the keyboard is shown below,
As you can see from the above GIF that when focusing on the anchor tags, a default blue outline is shown for each anchor tag.
We aim to change this outline color to a red
color and also want to increase its outline thickness by 3px
.
To do that first, we can select all the a
HTML elements in the CSS stylesheet using the a
selector and then use the :focus-visible
pseudo-class on the selector.
It can be done like this,
<html>
<style>
/* Using the `a` selector and using the `:focus-visible` pseudo-class */
a:focus-visible {
/* styles to trigger when focussed using the tab key can be written here */
}
</style>
<!-- A simple webpage with 3 anchor tags -->
<body>
<a href="#">Home</a>
<a href="#">About Us</a>
<a href="#">Privacy Policy</a>
</body>
</html>
We have defined the :focus-visible
pseudo-class on the a
selector.
Now let's change the color of the outline when the anchor tag is focused using the tab key.
To do that we can use the outline
CSS property and then use 3px solid red
as the value (3px
refers to the width of the outline, solid
refers to the style of the line and red
refers to the color of the outline) inside the :focus-visible
pseudo-class code block.
It can be done like this,
<html>
<style>
/*
Using the `a` selector and using the `:focus-visible` pseudo-class
to change the outline style of the anchor tag when focused using the tab key
*/
a:focus-visible {
outline: 3px solid red;
}
</style>
<!-- A simple webpage with 3 anchor tags -->
<body>
<a href="#">Home</a>
<a href="#">About Us</a>
<a href="#">Privacy Policy</a>
</body>
</html>
The anchor HTML element now looks like this on the webpage when focused using the tab key,
We have successfully changed the outline color of all the a
HTML elements on the webpage to red color. Yay 🥳!
Like this, we set the styles to any HTML elements in the webpage.
See the above code live in codesandbox.
That's all 😃.