The :focus
pseudo class in CSS is used for styling an element that is currently targeted by the keyboard, or activated by the mouse. Here is an example:
textarea:focus { background: pink; }
And here’s what that code looks like in action:
Any element (most commonly <input>
s and <textarea>
s) are in “focus” when they are selected and ready to enter text (like when a cursor is blinking.
“Tabbing”
Another use of the :focus
pseudo class is “tabbing” through elements. Many browsers have a default focus state for tab selection, which is a dotted outline. It is quite easy to remove, but make sure to replace it with a suitable alternative if you do.
<a>
s, <button>s
, <input>s
, and textareas
all have the :focus
state by default, but you can give a focus state to any element in HTML5. Both the contenteditable
and tabindex
attributes work for this, as in this example:
<h1>HTML5 Methods for Making Things Tab-able</h1> <p>All of the items below are tabbable. The text area and button are tabbable by default, and the divs use two different methods.</p> <textarea tabindex="1">A textarea. Focus states work by default.</textarea> <button tabindex="2">And I'm a button. Again, works by default.</button> <div contenteditable tabindex="3">Divs don't usually have a focus state. But I'm special, because I'm <code>contenteditable</code>.</div> <div tabindex="4">I'm another div, and I have a <code>tabindex</code>. You can't edit me like the div above, but you can tab to me.</div> <textarea tabindex="-1">I can't be tabbed to. This is a terrible idea, generally, but it can be done using tabindex="-1". Notice that (if you click) I still have a focus state, even though you can't tab to me.</textarea>
:focus { background: pink; } div { margin: 16px 0; } textarea { width: 500px; } button { margin: 16px 0; display: block; }
Browser Support
Chrome | Safari | Firefox | Opera | IE | Android | iOS |
---|---|---|---|---|---|---|
2+ | 1.3+ | Any | 9.2+ | 8+ | Any | Any |
Leave a Reply