Steps for smoothly changing the color of nested children at the same time

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>

Answer №1

The overall performance of the universal selector has shown significant improvement, although there are still some concerns, albeit minor. It is recommended to utilize .parent div if all children are <div> elements.

CSS:

div {
  font-size: 3rem;
  text-indent: 1rem;
}

.child {
  color: blue;
}

.parent,
.parent div {
  transition: all 3s;
}

.parent:hover,
.parent:hover div {
  color: red;
}

HTML:

<div class="parent">
  Level 1
  <div>
    Level 2
    <div class="child">
      Level 3 (!important means this should become red on hover)
    </div>
  </div>
</div>

Visit this JSFiddle link.

edit

To prevent recursive transition delays, specify the color for child elements explicitly, such as in the case of the blue .a-child:

div {
  padding-left: 1rem;
}

.parent * {
  color: black; /* explicitly set color of children */
  transition: color 2s;
}

.a-child { color: blue; }

.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>

The reason behind the recursive delay is that the parent's color setting remains red until the transition is completed, and only then reverts back to its default (inherited from <body>, which is black).

Since the second-level <div> does not have its color explicitly defined, it inherits the value from its parent, leading to a delay effect as it waits for the transition of the parent to complete and adopt the black color before transitioning itself.

This explains why the blue <div> immediately starts transitioning to blue when the mouse hovers off, as its color property is explicitly set to blue.

Answer №2

Utilizing the * selector and separating your .parent text into a distinct div allows you to target every child element of the parent for applying transitions and color changes.

Separating the content within the .parent div resolves any delays in the transition effect.

CSS

.parent * {
  transition: all 2s ease-out;
}

.parent:hover * {
  color: red;
}

HTML

<div class="parent">
  <div>Level 1</div> <!-- <-- Place in div -->
  <div>
    ...

This approach eliminates the necessity for using !important.

div {
  font-size: 3rem;
  text-indent: 1rem;
}
.child {
  color: blue;
}

.parent * {
  transition: all 2s ease-out;
}

.parent:hover * {
  color: red;
}
<div class="parent">
  <div>Level 1</div>
  <div>
    Level 2
    <div class="child">
      Level 3
    </div>
  </div>
</div>

JSFiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

Creating easy and efficient forms using Bootstrap

I'm currently working on creating a simple form and I've managed to set it up and make it "functioning" following the guidelines from Bootstrap documentation. Here's the code snippet: <form class="form-horizontal"> <fieldset> &l ...

Attempting to invoke the get method following the post method within a Django class-based view

After creating a classview for uploading files to azure blobstorage, displaying a table of uploaded file history, and enabling display on the page, I encountered an issue. The problem arises when a file is uploaded using the POST method but not executed by ...

I am having trouble viewing an image on my screen

I am trying to add an icon to the left side of my "Skriv ut" text, but unfortunately it is not displaying correctly. This is how I want it to look: https://i.stack.imgur.com/6jcne.png Here is the code snippet I am using: <div class="col-md-4 col-md-o ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

the replication of a column within one single column

I have discovered that in order to arrange items in a column using bootstrap-5, the code should look like this: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c1ccccd7d0d7d1c2d ...

What is the best way to ensure only one checkbox is selected at a time in a ReactJS application?

Currently, I am receiving an array of 3 language options from the API and mapping them. While they are displaying correctly at the moment, I want to have only one selected out of the three at any given time. https://i.sstatic.net/rathU.png Language Compon ...

Creating a CSS style that automatically adjusts the font size within a container that spans the full height of the

Issue: I have a container set to 100vh, but as the screen size changes, I want the font size to adjust accordingly and always stay within the container without overflowing. Thoughts: While I understand this can be achieved easily with @media CSS rules, I& ...

Input Form Label inexplicably rounded off at odd location

I've been utilizing Bootstrap to style my page, and I used the input form classes provided by Bootstrap to create this input field. However, upon loading the page, I noticed some strange rounding occurring between the label and the input space. http ...

What is the significance of using flexGrow in the parent div of a Material UI grid?

I am currently working on understanding a code example located at https://codesandbox.io/s/9rvlm which originates from the Material UI documentation (https://material-ui.com/components/grid/): import React from 'react'; import PropTypes from &ap ...

Having trouble getting the Vue checkbox change event to work?

I am currently utilizing Vue to handle a function that is not triggering on the change event when a checkbox is checked. I am uncertain if the issue lies in the fact that I have placed it within the mounted lifecycle hook or if there is another underlying ...

Bootstrap: nav-link remains visible even after a dropdown-item is chosen

I am aiming to accomplish the following - when a dropdown-item from the navbar is selected, I want to execute BOTH of the following actions: Scroll to the div with the specified target id Collapse the navbar back to its initial state (fully rolled up, hi ...

What is the best way to toggle the visibility of a div using a button? And how can you incorporate a visual effect on the button when

I'm trying to implement a button that can hide and show a div, but for some reason, it only shows the div and doesn't hide it when clicked. Check out my fiddle: http://jsfiddle.net/4vaxE/24/ This is my code: <div class="buttons" style="bac ...

Unable to load new page using Selenium and Chromedriver

Currently, I am in the process of learning how to utilize Selenium with Python. As a beginner exercise, I have been attempting to click a button on a webpage. Although I have been able to successfully locate the button and click on it, an unusual issue ari ...

Ensure each checkbox within a list is selected

My dilemma involves an assortment of checkboxes enclosed within LIs and SPANs in an unordered list. To simplify the checking process, I attempted using jQuery to automatically check all boxes when a button positioned above the UL is clicked. However, my ...

Spacing Between Bootstrap Columns

Is there a way to add a gap between each column while still maintaining 4 columns per row? When I try using the margin property, the columns do not align properly. Can you suggest a solution? <style> .test { border: 5px solid red; } </style&g ...

Leverage Selenium to scrape the Strava Leaderboard Table

When I try to extract a table from this page, I encounter some difficulties. The goal is to scrape the "This Week's Leaderboard," but extracting the table seems to be challenging. How can I efficiently retrieve the table without resorting to using reg ...

Navigating tables with Selenium WebDriver

I am struggling to locate and interact with a specific element in a table using Selenium WebDriver. The issue is that the table IDs are constantly changing, making it difficult for me to click on the desired element. For instance, consider the following t ...

Experimenting with creating collapsible panels using Bootstrap/CSS can result in various outcomes

, I am in the process of constructing a collapsible sliding left panel using bootstrap 5. The progress has been notable, but I am encountering some hurdles. Upon reviewing the code at this link: https://jsfiddle.net/dizzy0ny/86wjas9L/108/, you will witness ...

What is the best method to locate a particular item using XPATH in case of duplicate values?

I'm facing an issue where two products are priced the same at 499 RS, but my code is consistently selecting the first product instead of the second one. How can I ensure that it selects the correct duplicate item in this scenario? ...