Why Doesn't My CSS Transition Work on Hidden Elements?

Mary-Kate Olsen
Release: 2024-11-15 06:29:02
Original
128 people have browsed it

Why Doesn't My CSS Transition Work on Hidden Elements?

CSS Transition Doesn't Work Initially on Hidden Elements

When attempting to animate a hidden element's property using CSS transitions, you may encounter an issue where the element instantly displays at its final position. This is due to the relationship between the CSS Object Model (CSSOM) and the Document Object Model (DOM).

The Role of Reflow and CSSOM

CSS transitions determine their initial state based on the computed styles of an element. However, when an element has display: none, the browser ignores its computed styles since the element is effectively invisible to the CSSOM.

In your scenario, when you trigger the transition on .b, it has no computed style, as it's hidden. Therefore, the transition cannot initialize properly.

Forcing a Reflow

To solve this issue, you can force the browser to update the computed styles of the hidden element before initiating the transition. This is done by triggering a reflow.

Reflow is the process where the browser recalculates the layout and computed styles of the entire page. This can be triggered by certain DOM methods or by the browser itself when necessary, such as when the screen refreshes.

Using the requestAnimationFrame() API, you can request the browser to perform a reflow just before the next paint operation occurs. This ensures that the computed styles of your element are up-to-date when the transition begins.

Updated Code

$('button').on('click', function () {
  $('.b').show(); // Apply display:block synchronously

  requestAnimationFrame(() => {
    // Force a reflow
    document.body.offsetHeight;

    // Trigger the transitions
    $('.b').css('right', '80%');
    $('.a').css('right', '80%');
  });
})
Copy after login

The above is the detailed content of Why Doesn't My CSS Transition Work on Hidden Elements?. 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