CSS focus Pseudo-Class

CSS focus Pseudo-Class can be implemented to select an HTML element that is currently focused on by your web page user. It is usually applied in the input elements of HTML forms and triggered when the user clicks it with the mouse to insert data.

Syntax:
selector:focus {
/* declarations */
}

Here is an example of how an HTML input element changes its background color when users focus on it.

Example:
<!DOCTYPE html>
<html>
<head>

    <style>
        body {
            background-color: #f3f3f3;
            color: #333;
            font-family: sans-serif;
            font-size: 14px;
        }
        
        form {
            box-shadow: 0 1px 3px rgba(50, 50, 93, .15), 0 1px 0 rgba(0, 0, 0, .02);
            border: 1px solid #d7d7d7;
            background-color: #FFF;
        }
        
        input[type=text],
        input[type=password] {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            box-sizing: border-box;
            box-shadow: 0 1px 3px rgba(50, 50, 93, .15), 0 1px 0 rgba(0, 0, 0, .02);
        }
        
        input:focus {
            background-color: aqua;
        }
        
        button {
            background-color: #4CAF50;
            color: #FFF;
            margin: 8px 0;
            border: none;
            cursor: pointer;
            box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);
            min-width: 90px;
            border-radius: 2px;
            padding: 10px 12px;
        }
        
        .container {
            padding: 12px;
        }
    </style>
</head>
<body>

    <h2>Sign in Form</h2>
    <form action="" method="post">
        <div class="container">
            <label>Username</label>
            <input type="text" name="uname" required>

            <label>Password</label>
            <input type="password" name="pass" required>

            <button type="submit">Sign in</button>
        </div>
    </form>

</body>
</html>

Scroll Back to Top