CSS :focus Pseudo Class

The :focus selects and styles the elements that are focused by the user.

Elements, such as <input>, <button>, and <textarea> can receive focus either by tabbing using the keyboard or by clicking.

Accessibility Concerns

The visual focus indicator should be accessible to all people. According to WCAG 2.1 SC 1.4.11 Non-Text Contrast, the visual focus indicator should be at least 3 to 1.

When removing the focus outline (visible focus indicator) always replace it with a focus outline that will pass WCAG 2.1 SC 1.4.11 Non-Text Contrast.

:focus {
  outline: none;
}

Version

CSS2 Spec

Selectors level 3

Selectors level 4

Syntax

:focus {
  css declarations;
}

Example of the :focus selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input:focus {
        background-color: #ccc;
      }
    </style>
  </head>
  <body>
    <h2>:focus selector example</h2>
    <form>
      Name:
      <input type="text" name="name"> Surname:
      <input type="text" name="surname">
    </form>
  </body>
</html>

Example of the :focus selector with the <label> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input[type=text] {
        width: 100px;
        -webkit-transition: width .2s ease-in-out;
        -moz-transition: width .2s ease-in-out;
        -o-transition: width .2s ease-in-out;
        transition: width .2s ease-in-out;
      }
      input[type=text]:focus {
        width: 150px;
        background-color: #eee;
      }
    </style>
  </head>
  <body>
    <h2>:focus selector example</h2>
    <form>
      <label for="search">Search:</label>
      <input type="text" name="search" id="search">
    </form>
  </body>
</html>

Browser support

chrome edge firefox safari opera
4.0+ 12.0+ 2.0+ 3.1+ 10.0+

Practice Your Knowledge

What is the function of the ':focus' pseudo-class in CSS?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.