CSS focus
Created By: chatGPT
In CSS, the
:focus
pseudo-class is used to apply styles to an element that has gained focus, typically through keyboard input or mouse interaction. This is particularly useful for improving accessibility and providing visual cues to users. For example, when a user clicks on an input field, it becomes focused, and you can style it accordingly.input:focus {
outline: 2px solid blue;
background-color: lightyellow;
}
To create accessible forms or UI components, use the
:focus
pseudo-class to ensure that users can easily identify which element is currently focused. Combine it with transitions for smoother visual effects and better user experience.button:focus {
outline: none;
border: 2px solid green;
transition: border-color 0.3s ease;
}
For custom elements, like links, you can also apply the focus state to enhance the design. Ensuring that the focused element stands out is critical for users navigating with a keyboard.
a:focus {
color: red;
background-color: yellow;
transition: background-color 0.2s ease;
}
Remember to test your styles in different web browsers to ensure that they behave consistently. The focus state can also be triggered programmatically using JavaScript, and it’s important to maintain a consistent style throughout your application.
document.getElementById('myInput').focus();