The :hover selector in CSS applies styles to an element while the cursor hovers over it. It's frequently employed to produce interactive effects or to draw attention to elements when they're being interacted with.
You can target an element with the :hover selector using its tag name, class, or ID.
For Example:
The background color in the previous example will turn red (#ff0000) when a user hovers over an element with the class "button," while the text color will turn white (#ffffff).
Various hover effects can be produced by combining the :hover selector with other CSS elements like font size, border, or transform. It's a potent tool for boosting your website or application's visual feedback and interactivity.
It has the following syntax:
Let's take some examples to understand hover by using CSS:
HTML Code:
CSS Code:
Explanation:
In the above example, we have a button with a class hover-button. The button's initial color combinations are a light grey background (#eaeaea) and dark grey text (#333333). When the mouse hovers over the button, the background color changes to red (#ff0000) and the text color to white (#ffffff).
With a duration of 0.3 seconds and an ease timing function, the transition property in the hover-button class ensures a fluid transition for the background color change when the mouse hovers over the button.
Other elements, such as links (<a>), images (<img>), divs (<div>), or any other element you want to make interactive, can use similar hover effects. You can create various hover effects suited to your design needs by changing the properties and values within the :hover selector.
HTML Code:
CSS Code:
HTML Code:
CSS Code:
The :hover pseudo-class can be used to change the color of text when the mouse pointer is placed over an element.
HTML Code:
<h2 class="heading">Welcome to CSS</h2>
CSS Code:
.heading {
color: black;
transition: color 0.3s ease;
}
.heading:hover {
color: blue;
}
Explanation
In this example:
The :hover pseudo-class can also be applied to container elements such as <div>. This is useful for highlighting cards, content boxes, and menu items.
HTML Code:
<div class="box">
Move the mouse over this box.
</div>
CSS Code:
.box {
width: 250px;
padding: 20px;
background-color: lightgray;
transition: background-color 0.3s ease;
}
.box:hover {
background-color: lightgreen;
}
Explanation
In this example:
The :hover pseudo-class can be used to show hidden content when the user places the mouse pointer over an element.
HTML Code:
<div class="container">
Hover over me
<p class="message">Welcome to CSS!</p>
</div>
CSS Code:
.message {
display: none;
}
.container:hover .message {
display: block;
}
Explanation
In this example:
We request you to subscribe our newsletter for upcoming updates.