The :FOCUS pseudo-class is a dynamic pseudo-class that works much like the :HOVER pseudo-class. While :HOVER applies when the cursor is held over a link, :FOCUS applies when a user has selected an interactive element by clicking on it or tabbing to it. A form element is said to have "focus" when a user clicks on it or tabs to it. Not surprisingly, :FOCUS is typically applied to form elements.
General Syntax for the Focus Pseudo-Class
element:focus { declarations... }
The following example illustrates the use of the :FOCUS pseudo-class. Note how the input field changes background color and border color when you click inside it. The menus and button are highlighted when they are activated.
Example Style sheet
input[type="text"]:focus,
textarea:focus,
select:focus {
outline: 2px solid blue;
background-color: #FFC;
}
input[type="button"]:focus {
outline: 2px dotted red;
}
Example Markup
<form action="http://bogus_bogus.com/bogus.cgi"
method="get" id="search">
<p>
Tab from field to field to see how the :FOCUS style
highlights the active field to indicate focus.
You can also click in each field to focus on it.
</p>
<p>
<input type="text" name="searchBox" id="searchBox"
size="25" value="Type some text here" />
</p>
<p>
<textarea name="desc" id="desc"
cols="50" rows="4">Enter your thoughts here ...
</textarea>
</p>
<p>
You can assign the :FOCUS pseudo-class to an element
that does not accept keyboard input, such as menus.
</p>
<p>
<select name="make" id="make" size="6" multiple="multiple">
<option>Audi</option>
<option>BMW</option>
<option>Chrysler</option>
. . .
<option>Volkswagen</option>
<option>Volvo</option>
</select>
</p>
<p>
<select name="bodyType" id="bodyType" size="1">
<option>2-door</option>
<option>4-door</option>
<option>Convertible</option>
. . .
<option>Truck</option>
<option>Van</option>
</select>
</p>
<p>
Using the :FOCUS pseudo-class, a button can be
highlighted when the button has focus.
</p>
<p>
<input type="button" value="Go ahead, make my day" />
</p>
</form>
Rendered Example
View the effects of the :FOCUS pseudo-class rules applied to the markup above.