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
Role of CSS :focus Selector
The CSS :focus pseudo-class selector is used to target and style an element when it receives focus through user interaction, such as clicking on an input field or navigating to it using the Tab key.
Syntax
selector:focus {
property: value;
}
Example: Styling Input Fields on Focus
The following example changes the background color of input fields when they receive focus −
<!DOCTYPE html>
<html>
<head>
<style>
input:focus {
background-color: lightblue;
border: 2px solid blue;
outline: none;
}
input {
padding: 8px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
</head>
<body>
<form>
Subject: <input type="text" name="subject"><br>
Student: <input type="text" name="student"><br>
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
A form with three input fields appears. When you click on any input field, it gets a light blue background and blue border, providing clear visual feedback about which field is currently active.
Example: Focus Styles for Different Elements
The :focus selector can be applied to various focusable elements −
<!DOCTYPE html>
<html>
<head>
<style>
button:focus {
background-color: orange;
transform: scale(1.1);
}
textarea:focus {
border-color: green;
box-shadow: 0 0 5px rgba(0, 255, 0, 0.5);
}
select:focus {
outline: 2px solid purple;
}
button, textarea, select {
margin: 10px;
padding: 8px;
}
</style>
</head>
<body>
<button>Click me</button>
<textarea placeholder="Enter your message"></textarea>
<select>
<option>Option 1</option>
<option>Option 2</option>
</select>
</body>
</html>
Three interactive elements appear: a button that scales and turns orange when focused, a textarea that gets a green border and glow effect when clicked, and a select dropdown with a purple outline when focused.
Conclusion
The :focus selector improves user experience by providing visual feedback when elements receive focus. It's essential for creating accessible and user-friendly web interfaces.
Advertisements
