CSS :focus Selector
The :focus CSS pseudo-class Selector is used to target the focused element ie., it selects an element that is currently focused by the user. This selector works on user input elements, generally used in forms, and is triggered as soon as the user clicks on it or taps on an element, or selects any keyboard events.
Syntax:
:focus {
// CSS property
}
Example: This example illustrates the :focus selector to target the selected element.
<!DOCTYPE html>
<html>
<head>
<style>
input:focus {
background-color: limegreen;
}
</style>
</head>
<body>
<h3>Fill this form</h3>
<form> Full name:
<input type="text"
placeholder="Enter Name"
name="name">
<br> User Id:
<input type="text"
placeholder="Enter Username"
name="uid">
<br> Password:
<input type="password"
placeholder="Enter Password"
name="pass">
<br>
<button type="button"
onclick="#">Sign Up</button>
</form>
</body>
</html>
Output:
Supported Browsers:
- Google Chrome 1.0
- Microsoft Edge 12.0
- Firefox 1.0
- Safari 1.0
- Opera 7.0
CSS :focus Selector – FAQs
What does the :focus selector do in CSS?
The :focus selector targets an element that is currently focused, such as when a user clicks on an input field or navigates to it using the keyboard.
How do I style an input field when it is focused?
Use the :focus selector, like input:focus { border-color: blue; }, to change the border color of an input field when it is focused.
Does the :focus selector work with all interactive elements?
Yes, the :focus selector can be applied to any interactive elements, such as <input>, <textarea>, <button>, and links.
Can the :focus selector be combined with other pseudo-classes?
Yes, the :focus selector can be combined with other pseudo-classes, like :hover or :active, for more specific styling.
Is the :focus selector supported by all browsers?
Yes, the :focus selector is widely supported by all modern browsers, including older versions.