Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Role of CSS :hover Selector
The CSS :hover selector is a pseudo-class that applies styles to an element when a user hovers over it with their mouse cursor. It's commonly used to create interactive effects on links, buttons, and other elements to enhance user experience.
Syntax
selector:hover {
property: value;
}
Example 1: Basic Link Hover Effect
The following example demonstrates how to change the background color of a link when hovering over it −
<!DOCTYPE html>
<html>
<head>
<style>
a:hover {
background-color: orange;
color: white;
padding: 5px;
text-decoration: none;
border-radius: 3px;
}
</style>
</head>
<body>
<a href="#">Hover over this link</a>
<p>Keep the mouse cursor on the above link and see the effect.</p>
</body>
</html>
A link appears on the page. When you hover over it, the background changes to orange with white text, padding, and rounded corners.
Example 2: Button Hover Effect
Here's how to create an interactive button with hover effects −
<!DOCTYPE html>
<html>
<head>
<style>
.btn {
background-color: #4CAF50;
color: white;
padding: 12px 24px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: all 0.3s ease;
}
.btn:hover {
background-color: #45a049;
transform: scale(1.05);
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<button class="btn">Hover Me</button>
</body>
</html>
A green button appears that changes to a darker green, scales up slightly, and gains a shadow effect when hovered over.
Key Points
- The
:hoverselector works on any HTML element, not just links - Use
transitionproperty for smooth hover animations - Hover effects only work on devices with pointing devices like mice
- Always ensure hover effects are subtle and don't interfere with usability
Conclusion
The :hover pseudo-class is essential for creating interactive web interfaces. It provides immediate visual feedback to users and makes websites more engaging and user-friendly.
Advertisements
