In CSS, :hover
is a pseudo-class that defines the styles to be applied when the mouse pointer hovers over an HTML element.
It is used to add user interaction, provide visual feedback, and enhance the user experience (UX).
:hover
Property:hover
UsageIn the example below, when the mouse pointer hovers over the text “Basic :hover
Usage” the link color changes.
a {
color: #333;
text-decoration: none;
}
a:hover {
color: #007bff;
text-decoration: underline;
}
Preview
Basic :hover Usagebutton {
background-color: #ff5722;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #1362eb;
}
By using the CSS transition
property, the color transition duration can be extended, creating a smoother transition effect.
For a detailed explanation on how to create a zoom effect using CSS, see: https://juniortoexpert.com/en/zoom-image-when-user-hover/
<style>
.card {
padding: 20px;
border: 1px solid #ccc;
display: inline-block;
transition: background-color 0.3s ease;
}
.card-text {
color: #333;
transition: color 0.3s ease;
}
.card:hover .card-text {
color: #e91e63;
}
</style>
<div class="card">
<h3>Card Title</h3>
<p class="card-text">The color of this text will change on hover.</p>
</div>
The color of this text will change on hover.
With the .card:hover .card-text
selector, only the .card-text
element inside the card is affected when the card is hovered. This method can be used for background, size, opacity, and all other styles.
:hover
<style>
.hover-test-menu {
list-style: none;
padding: 0;
margin: 0;
}
.hover-test-menu > li {
position: relative;
background: #3498db;
color: white;
padding: 10px;
cursor: pointer;
width: 150px;
}
/* The submenu is initially hidden. */
.hover-test-submenu {
display: none;
position: absolute;
top: 100%;
left: 0;
list-style: none;
padding: 0;
margin: 0;
background: #2980b9;
width: 150px;
}
.hover-test-submenu li {
padding: 10px;
color: white;
}
/* Show the submenu on hover. */
.hover-test-menu > li:hover .hover-test-submenu {
display: block;
}
</style>
<ul class="hover-test-menu">
<li>
Main Menu
<ul class="hover-test-submenu">
<li>Sub Menu 1</li>
<li>Sub Menu 2</li>
<li>Sub Menu 3</li>
</ul>
</li>
</ul>
:hover
transition
property to soften the effects.:hover
work on mobile (touch) devices?:hover
does not work on mobile devices.