CSS :focus - Style FORM ELEMENT on Focus

The CSS :focus pseudo-class is used when we need to apply styles to an element during mouse-cursor focus. The :focus is used to change the effect of a field, where user is allowed to provide inputs, such as INPUT field of a FORM or a search box.

CSS :focus Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        input:focus {background-color: green; color: white;}
    </style>
</head>
<body>

    <h2>CSS :focus Pseudo-Class</h2>
    <form>
        Username: <input type="text" name="user"><br/>
        Password: <input type="password" name="pass"><br/>
    </form>
    
</body>
</html>
Output

CSS :focus Pseudo-Class

Username:
Password:

Note - The :focus is used when we need to style INPUT field, when the field gets focused.

To apply styles to a particular INPUT field of an HTML FORM, for example, to apply styles to INPUT field with only text type value, use following code:

input[type="text"]:focus {background-color: green; color: white;}

Or to apply styles to an input field with name user, then use following code:

input[name="user"]:focus {background-color: green; color: white;}

CSS Code to Expand Input Field on Focus

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        input {width: 100px; background-color: #ccc;}
        input:focus {width: 200px;}
    </style>
</head>
<body>

    <form>
        Search: <input type="text" name="search">
    </form>
    
</body>
</html>
Output
Search:

Click on the input field to increase its size from 100px to 200px.

CSS Online Test


« Previous Tutorial Next Tutorial »