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%'); }); })
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!