Skip to content

CSS :focus Pseudo Class

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

Elements, such as <input>, <button>, and <textarea>, can receive focus either by tabbing with the keyboard or by clicking. Non-interactive elements can also receive keyboard focus if they include a tabindex="0" attribute.

Accessibility Concerns

The visual focus indicator should be accessible to all users. According to WCAG 2.1 SC 2.4.7 Focus Visible, the focus indicator must be clearly visible and maintain a contrast ratio of at least 3:1 against adjacent colors.

When removing the default focus outline, always replace it with a custom indicator that meets WCAG 2.1 SC 2.4.7 requirements.

For better user experience, consider using the :focus-visible pseudo-class instead of :focus. It applies styles only when the element is focused via keyboard, avoiding unnecessary visual changes when using a mouse or touch.

CSS :focus Pseudo Class

css
:focus {
  outline: none;
}

Version

CSS2 Spec

Selectors level 3

Selectors level 4

Syntax

CSS :focus syntax example

css
:focus {
  css declarations;
}

Example of the :focus selector:

CSS :focus code example

html
<!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:

CSS :focus another code example

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input[type=text] {
        width: 100px;
        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>

Practice

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

Dual-run preview — compare with live Symfony routes.