Pseudo-classes are keywords added to selectors that specify a special state of the selected element(s). User action pseudo-classes, in particular, apply styles to elements based on how the user is interacting with them. This allows for dynamic and responsive interfaces that provide visual feedback to the user.
:hover
The :hover
pseudo-class applies styles to an element when the user's mouse cursor is positioned over it. It is commonly used to indicate that an element is interactive.
Example 1: Button Hover Effect
/* Style for a button */
.my-button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
transition: background-color 0.3s ease;
}
/* Style for the button on hover */
.my-button:hover {
background-color: #0056b3;
}
Explanation
This code changes the background color of the button when a user hovers over it, providing clear visual feedback. The transition
property creates a smooth color change.
Example 2: Link Underline Effect
/* Style for a link */
.my-link {
color: #007bff;
text-decoration: none;
position: relative;
}
/* Create a pseudo-element for the underline on hover */
.my-link:hover::after {
content: '';
position: absolute;
width: 100%;
height: 2px;
background-color: #007bff;
left: 0;
bottom: -5px;
}
Explanation
Instead of the default underline, this example adds a custom underline using a pseudo-element when the link is hovered. This allows for more creative control over the underline's appearance.
Example 3: Image Opacity Change
/* Style for an image */
.my-image {
opacity: 1;
transition: opacity 0.3s ease;
}
/* Change the opacity of the image on hover */
.my-image:hover {
opacity: 0.7;
}
Explanation
This code reduces the opacity of an image when the user's cursor is over it. This effect can be used to indicate that the image is part of a gallery or can be clicked.
Example 4: Div Shadow on Hover
/* Style for a div */
.my-card {
width: 200px;
height: 150px;
background-color: #f8f9fa;
border: 1px solid #dee2e6;
transition: box-shadow 0.3s ease;
}
/* Add a box shadow to the div on hover */
.my-card:hover {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
Explanation
When a user hovers over the div
, a subtle box-shadow
is applied. This is a common technique for lifting elements on a page and indicating interactivity.
Example 5: Change Child Element Style on Parent Hover
/* Style for a container and a hidden paragraph */
.container {
position: relative;
}
.container p {
visibility: hidden;
opacity: 0;
transition: opacity 0.3s ease;
}
/* Make the paragraph visible when hovering over the container */
.container:hover p {
visibility: visible;
opacity: 1;
}
Explanation
This example demonstrates how hovering over a parent element (.container
) can affect a child element. The paragraph inside the container becomes visible only when the container is hovered.