Can anyone help me with finding the CSS code that can change the color of all child elements with a transition effect? I have set up a simple test case in this JSFiddle:
<div class="parent">Level 1
<div>Level 2
<div class="child">Level 3 (!important means this should become red on hover)
</div>
</div>
</div>
I am struggling to come up with the CSS code to smoothly transition the text color. Below is what I have so far:
.parent {
transition: all 2s ease-out;
}
.parent:hover {
color: red !important;
}
.child {
color: blue;
}
I want to define a rule at the parent level to change the color of all children. While using !important
may not be recommended, it feels necessary in this case as it indicates an error state and overrides other rules.
I currently have a workaround but it involves setting rules for each child element which might not be ideal in a complex system where all affecting classes are unknown.
To achieve this without specifying all child classes, I tried using a .parent *
selector, but the transition duration increases with nesting levels as seen in this fiddle.
Update
I now understand that the issue lies in the additive nature of the transition-duration property for children. The goal is to have all nested elements transition simultaneously. Here's an example:
div {
padding-left: 1rem;
}
.a-child { color: blue; }
.parent * {
transition: color 2s;
}
.parent:hover * {
color: red;
}
<div class="parent">
<div>
Level 1
<div>
Level 2
<div>
Level 3
<div>
Level 4
<div class="a-child">
Level 5
</div>
</div>
</div>
</div>
</div>
</div>