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.

Version

CSS2

Syntax

:focus {
  css declarations;
}

Example

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

Another example with the :focus selector:

Example

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

4.0+ 12.0+ 2.0+ 3.1+ 10.0+

Practice Your Knowledge

Which statement below is incorrect?




Related articles