CSS :focus Pseudo Class

CSS :focus Pseudo Class

CSS :focus Pseudo Class


The: focus selects and styles the elements that are focused on 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>
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close