:focus

Avatar of Sara Cope
Sara Cope on (Updated on )

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;
}

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). Mouse users can click them (or their related label) to focus, and keyboard users can TAB into them.

“Tabbing”

nother 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 HTML. Both the contenteditable and tabindex attributes work for this, as in this example:

Other Resources

Browser Support

All browsers support basic usage of :focus.