Grow your CSS skills. Land your dream job.

:focus

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

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:

Check out this Pen!

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
2+ 1.3+ Any 9.2+ 8+ Any Any

Comments

  1. Your Name
    Permalink to comment#

    test

  2. Permalink to comment#

    what is use of :focus

  3. Thanks for that dude! Worked fine for me :)

  4. is it possible to :focus on two elements?

  5. Very good info bro!

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".