Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Usage of CSS :focus pseudo-class
The CSS :focus pseudo-class is used to apply styles to form elements when they receive focus (when a user clicks on them or navigates to them using the keyboard). This is particularly useful for improving user experience and accessibility.
Syntax
selector:focus {
property: value;
}
Example
The following example demonstrates how to use the :focus pseudo-class to highlight input fields with an orange background when they are focused −
<!DOCTYPE html>
<html>
<head>
<style>
input:focus {
background-color: orange;
outline: 2px solid #ff6600;
border-radius: 4px;
}
input {
padding: 8px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
form {
max-width: 300px;
padding: 20px;
}
</style>
</head>
<body>
<form>
<label>Subject: <input type="text" name="subject"></label><br>
<label>Student: <input type="text" name="student"></label><br>
<label>Age: <input type="number" name="age"></label><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
A form with three input fields appears. When you click on or tab to any input field, it gets an orange background with an orange outline, making it visually distinct and clearly indicating which field is currently active.
Common Use Cases
The :focus pseudo-class is commonly used for:
- Highlighting active form fields
- Improving keyboard navigation accessibility
- Providing visual feedback to users
- Creating consistent focus indicators across forms
Conclusion
The :focus pseudo-class is essential for creating accessible and user-friendly forms. It helps users identify which element is currently active and improves the overall user experience.
Advertisements
