Home >Web Front-end >CSS Tutorial >Can I Style a Parent Element on Child Element Hover in CSS?

Can I Style a Parent Element on Child Element Hover in CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 15:06:20404browse

Can I Style a Parent Element on Child Element Hover in CSS?

Styling Parent Elements on Child Element Hover

Question: Is it possible to modify the appearance of a parent element when hovering over a child element, even without a dedicated parent selector in CSS?

Context: Consider a scenario with a "Delete" button. When the user moves the cursor over the button, we want to highlight the parent section it's contained in.

Answer:

While a true parent selector doesn't exist in CSS, there are methods to achieve the desired effect using Cascading Layers (z-index) or pseudo-wrappers.

Pseudo-Wrapper Method:

This method involves creating a pseudo-wrapper element that acts as an invisible layer on top of the parent. When the mouse hovers over the child element, it interacts with the pseudo-wrapper, which in turn triggers CSS changes on the parent.

Code:

div.parent {
  z-index: 0;
}

div.child {
  z-index: 1;
  pointer-events: auto;
}

div.child:hover + div.parent {
  background-color: yellow;
}

Explanation:

  • We assign a low z-index to the parent, ensuring it's below the child.
  • The child has a higher z-index and pointer-events set to auto, allowing mouse events to pass through.
  • When the child is hovered, the adjacent sibling selector ( ) targets the parent and applies a yellow background color.

The above is the detailed content of Can I Style a Parent Element on Child Element Hover in CSS?. 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