CSS :focus-visible
The CSS :focus-visible pseudo-class applies styles to an element when it receives focus, but only if the focus is visible. This pseudo-class is typically triggered when a user interacts with an element using a keyboard or other assistive technologies. It prevents focus styles from being displayed when interacting with elements via a mouse.
The syntax for the :focus-visible
pseudo-class is:
selector:focus-visible {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The element to which the :focus-visible pseudo-class will apply when it has visible focus. |
property | The CSS property to style the element. |
value | The value assigned to the CSS property. |
Examples
1. Styling Focused Buttons
In this example, buttons are styled with a blue outline when they receive keyboard focus.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
button:focus-visible {
outline: 2px solid blue;
outline-offset: 2px;
}
</style>
</head>
<body>
<button>Click Me</button>
<button>Submit</button>
</body>
</html>
2. Highlighting Input Fields
Here, input fields are highlighted with a green border when they receive focus via keyboard navigation.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:focus-visible {
border: 2px solid green;
border-radius: 4px;
}
</style>
</head>
<body>
<form>
<label>Name:</label>
<input type="text" placeholder="Enter your name"><br><br>
<label>Email:</label>
<input type="email" placeholder="Enter your email">
</form>
</body>
</html>
3. Styling Links with Focus
In this example, links are styled with a background color when focused using a keyboard or assistive technology.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
a:focus-visible {
background-color: lightblue;
text-decoration: underline;
}
</style>
</head>
<body>
<a href="#section1">Go to Section 1</a><br>
<a href="#section2">Go to Section 2</a>
</body>
</html>
4. Customizing Focus Styles for Textareas
Here, textareas are styled with a box shadow when they receive focus via keyboard input.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
textarea:focus-visible {
box-shadow: 0 0 5px rgba(0, 128, 0, 0.8);
border: 1px solid rgba(0, 128, 0, 0.8);
}
</style>
</head>
<body>
<textarea rows="4" cols="30" placeholder="Write your message here..."></textarea>
</body>
</html>
5. Styling a Search Bar with Focus
In this example, a search bar input field is styled with a background color and bold border when focused using a keyboard.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input[type="search"]:focus-visible {
background-color: #f0f8ff;
border: 2px solid #1e90ff;
}
</style>
</head>
<body>
<form>
<input type="search" placeholder="Search here...">
<button>Search</button>
</form>
</body>
</html>