CSS :focus Selector

CSS :focus selector is used to select and style a focused element. An element(mostly <input> & <textarea>) is in focus when the user clicks on it and it’s ready to enter the text. This can be done either by clicking on it using the mouse pointer or simply by pressing a TAB key.

The following example sets a cyan color background to the <input> element when it gets focused:

Example:

input:focus{
    background-color: cyan;
}

Similarly, you can add styles to the <textarea> element also when it is in focus.

See this example:

Example:

textarea:focus{
    background-color: cyan;
}

HTML buttons do also allow the focusing behavior when they are clicked. Just like the <input> and <textarea> elements, you can also add styles to the buttons when they are in focus.

In the following example, we have added a red color 2px shadow to the buttons whey they are in focus.

Example:

button:focus{
    box-shadow: 2px 2px 10px red;
}

CSS Syntax

The syntax of the :focus selector is as follows:

:focus{
   CSS Styles;
}

Browser Support

The number in each cell of the table specifies the first version of the browser that fully supports the :focus selector.

Selector
:focus4.08.02.03.19.6

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts