CSS :focus

The CSS :focus pseudo-class applies styles to an element when it gains focus, typically through user interaction such as keyboard navigation or programmatic focus using JavaScript. It is commonly used to enhance accessibility and improve user experience by visually indicating the focused element.

The syntax for the :focus pseudo-class is:

</>
Copy
selector:focus {
    property: value;
}

Where:

ParameterDescription
selectorThe HTML element to which the focus effect will be applied.
propertyThe CSS property to be changed when the element is focused.
valueThe value assigned to the CSS property during the focus state.

Examples

1. Changing Input Border Color on Focus

In this example, the border color of an <input> element changes to blue when focused.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        input:focus {
            border-color: blue;
            outline: none;
        }
    </style>
</head>
<body>
    <input type="text" placeholder="Focus me">
</body>
</html>

2. Highlighting a Textarea on Focus

Here, the background color of a <textarea> changes to lightyellow when focused.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        textarea:focus {
            background-color: lightyellow;
        }
    </style>
</head>
<body>
    <textarea placeholder="Focus me"></textarea>
</body>
</html>

3. Enlarging a Button on Focus

In this example, a button increases in size slightly when focused, creating a zoom effect.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        button:focus {
            transform: scale(1.1);
            transition: transform 0.3s;
        }
    </style>
</head>
<body>
    <button>Focus me</button>
</body>
</html>

4. Changing Link Underline Style on Focus

When a link is focused, its underline style changes to a dotted line.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        a:focus {
            text-decoration: underline dotted;
        }
    </style>
</head>
<body>
    <a href="#">Focus this link</a>
</body>
</html>