The :focus
pseudo-class applies styles to an element that has received focus, either through a mouse click or by tabbing with the keyboard. It is commonly used on form elements like <input>
, <textarea>
, and <select>
.
Example 1: Input Focus
/* Style for an input field */
.my-input {
border: 1px solid #ced4da;
padding: 8px;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
}
/* Add a colored border and shadow when the input is focused */
.my-input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
Explanation
When a user clicks on or tabs to the input field, the default outline is removed, and a blue border with a subtle glow is added, improving the visual cue for the focused element.
Example 2: Textarea Focus
/* Style for a textarea */
.my-textarea {
border: 1px solid #ced4da;
padding: 8px;
transition: background-color 0.3s ease;
}
/* Change the background color of the textarea when it is focused */
.my-textarea:focus {
background-color: #f8f9fa;
}
Explanation
This code changes the background color of the textarea
when it receives focus, making it clear to the user which field they are currently editing.
Example 3: Link Focus
/* Style for a link */
.my-link {
color: #007bff;
text-decoration: none;
padding: 5px;
border-radius: 3px;
}
/* Add a background color to the link when it is focused */
.my-link:focus {
background-color: #e9ecef;
outline: 2px solid #007bff;
}
Explanation
For accessibility, it's important to style the focus state of links. This example adds a background color and a distinct outline when a link is focused via the keyboard.
Example 4: Div with tabindex Focus
/* Style for a focusable div */
.focusable-div {
padding: 20px;
border: 2px dashed #6c757d;
}
/* Change the border style and color when the div is focused */
.focusable-div:focus {
outline: none;
border-style: solid;
border-color: #6c757d;
}
Explanation
By adding a tabindex="0"
attribute to the div
in the HTML, it becomes focusable. This CSS then changes the border from dashed to solid when the user tabs to the div
.
Example 5: Animated Border on Focus
/* Style for an input field */
.animated-input {
border: 2px solid transparent;
background-image: linear-gradient(white, white),
linear-gradient(to right, #007bff, #28a745);
background-origin: border-box;
background-clip: padding-box, border-box;
}
/* Animate the border on focus */
.animated-input:focus {
animation: rotate-border 1.5s linear infinite;
}
@keyframes rotate-border {
to {
transform: rotate(360deg);
}
}
Explanation
This advanced example uses a background gradient to create a colored border. When the input is focused, a CSS animation rotates the gradient, creating a visually engaging effect.