EN
CSS - add style to the parent element when hovering child
3
points
In this article, we would like to show you how to add style to the parent element when hovering child using CSS.
![Hover effect on parent on on hover on child using CSS.](/static/bucket/1668613328759-k7AN9wdD90--css_hove_on_parent_on_child_v2.gif)
Quick solution:
.parent {
pointer-events: none; /* disables the hover on the .parent */
}
.parent:hover { /* styles for parent element when hover is on .child */
/*
Put parent hover styles here ...
*/
}
.parent .child {
pointer-events: auto; /* enables the hover on the .parent */
}
.parent .child:hover { /* styles for child element when hover is on .child */
/*
Put child hover styles here ...
*/
}
Practical examples
In this examples, we use pointer-events
property to manipulate the pointer events on .parent
and .child
elements. In the examples by default parent has disabled pointer events (pointer-events: none
) and child element forces to enable pointer-events
back on the parent.
When we move mouse over parent element, hover doesn't work. When we move mouse over child, it works both for the parent and the child.
Example 1
// ONLINE-RUNNER:browser;
<html>
<head>
<style>
.parent {
pointer-events: none; /* disables the hover on the .parent */
}
.parent:hover { /* styles for parent element when hover is on .child */
background: silver;
}
.parent .child {
pointer-events: auto; /* enables the hover on the .parent */
}
.parent .child:hover { /* styles for child element when hover is on .child */
color: yellow;
}
</style>
</head>
<body>
<div class="parent">
Some text in parent ...
<div class="child">Put mouse over...</div>
Some text in parent ...
</div>
</body>
</html>
Example 2
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.parent {
padding: 20px;
background: gold;
pointer-events: none; /* disables the hover on the .parent */
}
.parent:hover { /* styles for parent element when hover is on .child */
background: yellow;
}
.child {
padding: 20px;
background: orange;
pointer-events: auto; /* enables the hover on the .parent */
}
.child:hover { /* styles for child element when hover is on .child */
/* Put child hover styles here ... */
}
</style>
</head>
<body style="display: flex;">
<div class="parent">
Parent!
<div class="child">Child!</div>
</div>
</body>
</html>