8.3 The :Focus Pseudo Class
The :focus pseudo-class is a dynamic selector that allows certain elements to be rendered differently whenever they gain focus, that is, in response to an action from a user. It is rather similar to the :hover pseudo class but it takes into account that not everybody uses the same input devices and control methods to navigate a website. While most will interact using a mouse, it is important to take into account those using a keyboard or other devices. There are several ways a user can give focus to an element:
The :focus pseudo-class can be used to create a variety of different effects, from a subtle styling change to a more obvious element toggling its visibility on the page. It can be used to make a site more accessible for users. Focus can be used on its own or in combination with the hover and active pseudo-class to aid a keyboard user, going beyond what a browser may implement by default. Some of the elements focus can be used on include:
| Element | Description |
|---|---|
| <a> | The anchor element used in links |
| <button> | The button element used in forms |
| <div> | The div element |
| <img> | The image element |
| <input> | The input element (when type=button, file, image, password, reset, submit or text |
| <span> | The span element |
| <table> | The table element |
| <td> | The table data element |
| <textarea> | The textarea element used in forms |
With links, a link that has focus is often depicted in many browsers by outlining the element with a dotted-border (note that Internet Explorer 7 and below does not natively render focus). The focus pseudo-class is applied to the end of the element in the CSS and is separated using a comma. For example:
a:hover, a:focus {text-decoration:none;}
The above will apply focus when the link is hovered over. More pseudo classses could be tagged onto this if required, such as :active. With elements that receive inout, such as the <input> tag, the distinction between hover and focus is simple: hover acts as expected, but for focus to take effect the inout field area must be clicked. The following style rule will change the background color of any element that receives input focus, such as form tags:
*:focus {background-color:#ffcccc;}
Or specific input tags can be specified:
input.highlight:focus {background:#ffff33;}
This would render any input fields with a yellow background. But to prevent it rendering all input fields in this way, we have added a CSS class called .highlight into the declaration. Try clicking the input field below:
Here we have combined pseudo classes with regular CSS classes with, which leads us nicely into the next section.