Home > OS >  CSS animation transform translateY also changing translateX, but is not specified in animation
CSS animation transform translateY also changing translateX, but is not specified in animation

Time:06-21

Here, I have a simple CSS file containing 2 animations.

.div
    transform: translateX(-50%);
}

.fade-in {
    animation-name: fade-in;
    animation-duration: .2s;
}

.fade-out {
    animation-name: fade-out;
    animation-duration: .2s;
}

@keyframes fade-out {
    0% {
        opacity: 100%;
    }
    100% {
        opacity: 0%;
        transform: translateY(-10px);
    }
}

@keyframes fade-in {
    0% {
        opacity: 50%;
        transform: translateY(-10px);
    }
    100% {
        opacity: 100%;
    }
}

Why is it that even though I only specified translateY in the animation keyframes, it also manipulates the translateX in the transform property? And how can I make it so it only changes the Y value?

CodePudding user response:

You override whole transform attribute - not just translate. If you want to keep your translateX value you have to include it in animation too.

@keyframes fade-out {
    0% {
        opacity: 100%;
        transform: translateX(-50%);
    }
    100% {
        opacity: 0%;
        transform: translateY(-10px) translateX(-50%);
    }
}

CodePudding user response:

it seems you forgot to add "{" in the first selector in your CSS and please it would be better if you show us the HTML

CodePudding user response:

You are overriding the transform peropty. Merge transform: translateX(-50%) and transform: translateY(-10px); by doing: transform: translate(-50%, -10px);

Do this:

.div {
  transform: translateX(-50%);
}
.fade-in {
  animation-name: fade-in;
  animation-duration: .2s;
}
.fade-out {
  animation-name: fade-out;
  animation-duration: .2s;
}
@keyframes fade-out {
  0% {
    opacity: 100%;
  }
  
  100% {
    opacity: 0%;
    transform: translate(-50%, -10px); /* NEW */
  }
}
@keyframes fade-in {
  0% {
    opacity: 50%;
    transform: translate(-50%, -10px); /* NEW */
  }
  
  100% {
    opacity: 100%;
  }
}

  • Related