Home > Blockchain >  Safari: CSS animation doesn't start second time when transitioning from display: none to displa
Safari: CSS animation doesn't start second time when transitioning from display: none to displa

Time:01-25

I have this simple animation triggered when transitioning from display: none to display: block. It works perfect on Chrome but on Safari it is triggered only for first time, when I hide element and then show it again second time, it is not working.

.child1 {
  display: none;
}

.child2 {
  display: block;
}

.visibility .child1 {
  display: block;
}

.visibility .child2 {
  display: none;
}

@keyframes myAnimation {
  0% { transform: scale(0.5); }
}

.animated {
  animation: myAnimation 0.4s ease-out;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

<div id="testdiv" >
    <div >Hello</div>
    <div >Bye</div>
</div>

<script>
    const elem = document.getElementById("testdiv");

    elem.addEventListener("click", () => {
        if (!elem.classList.length) {
            elem.classList.add("visibility");
        } else {
            elem.classList.remove("visibility")
        }
    })
</script>
</body>
</html>

CodePudding user response:

Here's the trick: give the animation a very small delay, let's say 0.0001s and there you go.

.animated {
  animation: myAnimation 0.4s ease-out 0.0001s;
}

As you're using CSS animation with display - a non-animatable property, different browsers will treat this in different ways and somehow unpredictable.

The reason it works when we put a small delay is that before the text slide from right to left, the text should not appear on the screen, hence, display: none. However, as I said, display is not animatable, so the text would appear immediately leading to no transition visible, what we do is to give it some time to disappear.

Anyway, this is still a trick, when you switch to another tab on Safari then get back, the animation will not run. It's better not to use display for animation.

  •  Tags:  
  • Related