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
Mary-Kate OlsenOriginal
2024-12-27 03:10:08707browse

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>

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;
}

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;
}

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!

Statement:
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