CSS :hover Selector
CSS :hover selector is used to select HTML elements when we move the mouse over them. It is useful when we want to give some motion effects on a website. It makes our website more interactive as compared to a normal website.
CSS :hover can be used on any HTML element, it is mostly used in 2D transform effect, to create a dropdown, mega menu and on image overlay, etc.
How to Use CSS :hover Selector
CSS :hover can be used in two ways:
- we can use :hover directly on the selected element.
- we can use :hover to give effect on child element when we mouse hover on the parent element. For example: in a dropdown.
Syntax:
element :hover
{
Property-name: value;
}
To give effect on child element when we mouse over on parent.
Syntax:
parent-element: hover child-element
{
Property-name:value;
}
Example1: :hover effect on selected element
<!DOCTYPE html>
<html>
<head>
<style>
a:hover
{
color:red;
}
</style>
</head>
<body>
<a href="#">web development institute</a>
<a href="#">Next-G Education</a>
</body>
</html>
Example2: :hover effect on child element when we mouse hover on parent element.
<!DOCTYPE html>
<html>
<head>
<style>
.parent
{
width:300px;
height:300px;
background:#ddd;
padding:50px;
}
.child
{
width:200px;
height:200px;
background:#f00;
}
.parent:hover .child
{
background:#000;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
In the above example, when you will mouse hover on parent div it will change the color of child div.