Home > Web Front-end > CSS Tutorial > How Can I Style Child Elements When Their Parent is Hovered Over Using CSS?

How Can I Style Child Elements When Their Parent is Hovered Over Using CSS?

Barbara Streisand
Release: 2024-11-30 02:04:12
Original
147 people have browsed it

How Can I Style Child Elements When Their Parent is Hovered Over Using CSS?

Targeting Child Elements on Parent Hover

Question:

How can we modify the styling of a child element when the parent element is hovered over, preferably using CSS? Is this achievable with :hover selectors?

Answer:

Yes, CSS provides a straightforward solution for this requirement. By utilizing the :hover pseudoclass and the descendant combinator, we can specifically target child elements within hovered parent elements.

.parent:hover .child {
   /* ... */
}
Copy after login

In this rule, the :hover pseudoclass applies to the .parent element when the cursor is hovering over it. The descendant combinator (space) then selects any descendant element that matches the .child class. This allows us to modify the style of the child element in response to the hovering of the parent element.

Furthermore, modern browsers support a wide range of CSS properties that can be modified for the child element, including color, font, background, and transitions. Here's an example to illustrate the concept:

.parent {
  border: 1px dashed gray;
  padding: 0.5em;
  display: inline-block;
}

.child {
  border: 1px solid brown;
  margin: 1em;
  padding: 0.5em;
  transition: all 0.5s;
}

.parent:hover .child {
  background: #cef;
  transform: scale(1.5) rotate(3deg);
  border: 5px inset brown;
}
Copy after login
<div class="parent">
  parent
  <div class="child">
    child
  </div>
</div>
Copy after login

The above is the detailed content of How Can I Style Child Elements When Their Parent is Hovered Over Using CSS?. 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