Pseudo-classes hover and focus

Pseudo-classes are used in CSS to define a special state of an element. They help you apply styles when a user interacts with a page, such as moving the mouse over a button or clicking into a form field.

What is hover

The hover pseudo-class is applied when a user places their mouse pointer over an element. It is commonly used for buttons, links, and images to improve user experience.

Example of hover

button:hover {
background-color: blue;
color: white;
}

In this example, the button changes color when the user moves the mouse over it.

What is focus

The focus pseudo-class is applied when an element is selected or activated, usually when a user clicks on an input field or navigates using the keyboard.

Example of focus

input:focus {
border: 2px solid green;
outline: none;
}

This highlights the input field when the user clicks on it or tabs into it.

Why hover and focus are important

Hover improves visual feedback and makes interfaces feel interactive. Focus is essential for accessibility, helping users who navigate with keyboards understand which element is active.

Best practices

Use hover effects to guide users but avoid overusing strong animations. Always include focus styles so that forms and buttons are accessible. Do not remove outlines unless you replace them with a clear visible style.

Practical example

<!DOCTYPE html>
<html>
<head>
<style>
a {
color: black;
text-decoration: none;
}a:hover {
color: red;
}input {
padding: 8px;
}input:focus {
border: 2px solid blue;
}
</style>
</head>
<body><a href="#">Hover over this link</a>
<br><br>
<input type="text" placeholder="Click here"></body>
</html>

This example shows how hover changes a link color and focus highlights an input field.

Summary

The hover and focus pseudo-classes make websites more interactive and user friendly. They are simple to use but very powerful for improving design and accessibility.