When creating web forms, it’s essential to provide visual feedback to users when they interact with form elements. One way to achieve this is by styling form elements, such as textareas and input fields, when they receive focus. In this tutorial, we’ll explore how to change the border color of a textarea on focus using CSS.
Understanding the :focus Pseudo-Class
The :focus
pseudo-class is used to select an element that has received focus. This can be triggered by clicking or tabbing into an element. To style an element on focus, you simply need to add the :focus
pseudo-class to your CSS selector.
Styling Textareas on Focus
To change the border color of a textarea on focus, you can use the following CSS code:
textarea:focus {
outline: none;
border-color: #719ECE;
box-shadow: 0 0 10px #719ECE;
}
In this example, we’re selecting all textarea
elements that have received focus and applying the following styles:
outline: none
: This removes the default outline that is applied to focused elements.border-color: #719ECE
: This changes the border color of the textarea to a blueish hue.box-shadow: 0 0 10px #719ECE
: This adds a subtle shadow effect to the textarea, which helps to create a sense of depth.
Styling Input Fields on Focus
You can also style input fields on focus using similar CSS code:
input:focus {
outline: none;
border-color: #719ECE;
box-shadow: 0 0 10px #719ECE;
}
Note that you can customize the styles to fit your specific design requirements.
Using the outline-color
Property
Alternatively, you can use the outline-color
property to change the color of the outline that is applied to focused elements. For example:
textarea {
outline-color: #719ECE;
}
This approach can be useful if you want to customize the outline color without removing it entirely.
Best Practices
When styling form elements on focus, keep the following best practices in mind:
- Use a consistent design language throughout your form.
- Ensure that your focused styles are accessible and visible to all users, including those with visual impairments.
- Test your focused styles across different browsers and devices to ensure compatibility.
By following these guidelines and using the CSS code examples provided in this tutorial, you can create visually appealing and user-friendly forms that provide a great experience for your users.