What is the CSS focus selector?
The CSS focus selector is a user action pseudo-class selector, which means it requires some interaction by the user to be used.
The CSS selector, combined with the :focus pseudo-class, is used to style an element that is targeted by the keyboard or focused on by the mouse.
Syntax
The syntax for the :focus selector is as follows:
css-selector:focus {
// css rules
}
The CSS selector can either be a class, ID, or HTML attribute. The :focus keyword specifies the element that receives focus either through keyboard or mouse events, as shown in the example below:
.container:focus{
border:1px solid black;
}
The container class is set to have a border when it is focused on.
Most form elements, such as <input> and <textarea>, have default focus styles, depending on the browser. In cases where users click or tab through using the keyboard, the default styles are displayed.
Code
The code below displays the default style of the <input> element when selected.
With the :focus selector, the style can be changed to our preference, as shown below:
It is important to note that accessibility must be prioritized in developing a user interface. For styling elements with the
:focusselector, the Web Content Accessibility Guidelines (WCAG) must be followed carefully.
Browser compatibility
The focus selector is limited to certain browsers, such as:
- Google Chrome 4.0
- Microsoft Edge 12.0
- Internet Explorer 8.0
- Firefox 2.0
- Safari 3.1
- Opera 9.6