Home > Web Front-end > CSS Tutorial > How Can I Style a Parent Element When Its Child is Hovered Without Using a Parent Selector?

How Can I Style a Parent Element When Its Child is Hovered Without Using a Parent Selector?

Mary-Kate Olsen
Release: 2024-12-27 03:10:08
Original
704 people have browsed it

How Can I Style a Parent Element When Its Child is Hovered Without Using a Parent Selector?

Styling Parent Elements on Child Hover Without a Parent Selector

In CSS, directly targeting parent elements based on child interactions is challenging due to the lack of a parent selector. However, there's a clever workaround that allows us to achieve this effect: creating a pseudo wrapper within the parent element.

Consider the example given, where a delete button highlights its parent section on hover:

<div>
    <p>Lorem ipsum ...</p>
    <button>Delete</button>
</div>
Copy after login

To highlight the parent section, we'll create a child div with pointer-events set to auto, while disabling it for the parent:

div.parent {
    pointer-events: none;
}

div.child {
    pointer-events: auto;
}
Copy after login

Now, the parent becomes transparent to mouse events, allowing the child div to trigger hover effects. And when a hover event occurs on the child, we can style the parent as desired:

div.parent:hover {
    background: yellow;
}
Copy after login

This technique ensures that the parent element responds to hover interactions on its child, effectively simulating a parent selector's behavior. Note that pointer-events: auto should be restored for other child elements with event listeners to maintain their functionality.

The above is the detailed content of How Can I Style a Parent Element When Its Child is Hovered Without Using a Parent Selector?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template