CSS animation in LWC not working
Was able to sort out a workaround to get this functioning. By importing a stylesheet with the keyframes in it, we can avoid the current impact of the compiler.
The 'third party library' examples in the developer docs gave me the hint for this technique.
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_third_party_library
Here's what the working component looks like now.
fadingText.css - Deleted
fadingText.html
<template>
<div class="animate-flicker">Some Text</div>
</template>
fadingText.js
import { LightningElement } from 'lwc';
import { loadStyle } from 'lightning/platformResourceLoader';
import styles from '@salesforce/resourceUrl/styles';
export default class FadingText extends LightningElement {
connectedCallback() {
loadStyle(this, styles)
}
}
styles.css - Uploaded as a static resource
.animate-flicker {
-webkit-animation: flickerAnimation 1s infinite !important;
-moz-animation: flickerAnimation 1s infinite !important;
-o-animation: flickerAnimation 1s infinite !important;
animation: flickerAnimation 1s infinite !important;
}
@keyframes flickerAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-o-keyframes flickerAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-moz-keyframes flickerAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-webkit-keyframes flickerAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
You have stumbled upon a bug in Lightning Web Components. When you write your CSS in the CSS file, Salesforce tries to do some optimisations to it like minifying it, adding attribute selectors (possibly to scope the CSS within the component).
When you define your keyframe offsets (0%
, 50%
, 100%
), Salesforce incorrectly thinks it is also a CSS selector and adds the attributes to them, rendering them syntactically incorrect that the browser doesn't understand.
Here's how Salesforce renders your CSS in the browsers after its optimisations:
Here's what the correct output from Salesforce should be for this to work (you can try editing the above output to the below one in Chrome Dev tool's Elements
tab and you will see the expected animation).