0

I have different views in my page that each have keyframe animations. Each section is shown or hidden by media queries.

Let's say theoretically I am pulling in a separate CSS stylesheet or that I have some limitations to the CSS. If I have two keyframe style rules with the same name "fadein" in this case, will I run into any issues? The last one declared wins correct? Or are style rules nested in a media query treated differently?

@media (min-width: 0px) {
    @keyframes fadein {

        0% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }

    }
}

@media (min-width: 800px) {
    @keyframes fadein {

        0% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }

    }
}

Is there a way to get a keyframe rule by name or id? Is the keyframe name an id?

In other words, you can use document.getElementById("myElement") to get the element using JavaScript but for keyframes is there a method? How does it work when two keyframe rules have the same name?

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • I don't think you can even define keyframes inside media query like you are doing – Temani Afif Oct 27 '19 at 08:16
  • 1
    possible duplicate of : https://stackoverflow.com/q/20407906/8620333 – Temani Afif Oct 27 '19 at 08:19
  • @TemaniAfif From that answer it looks like, "...keyframes, once defined, cannot be overwritten or reassigned based on media queries...". I'll have to do some testing to confirm that. I had wondered if each media query used it's own local scoped keyframe rule first. An answer below says that the last one defined wins. – 1.21 gigawatts Oct 27 '19 at 19:54
  • @TemaniAfif In CSS 2.1 nested @ rules were not supported but from what I've read they've changed that in CSS 3 https://stackoverflow.com/a/11747166/441016 – 1.21 gigawatts Oct 27 '19 at 20:07

1 Answers1

1

The name is the identifier of the keyframe set and should be unique (unless you need to override it for some reason):

If multiple keyframe sets exist for a given name, the last one encountered by the parser is used. @keyframes rules don't cascade, so animations never derive keyframes from more than one rule set. (source MDN)

So, I think it would be better to avoid too generic names, and possibly namespace your keyframe sets. For example, in your case:

@keyframes namespace_fadein_small {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes namespace_fadein_large {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@media (min-width: 0px) {
  .fading {
    animation-name: namespace_fadein_small;
  }
}
@media (min-width: 800px) {
  .fading {
    animation-name: namespace_fadein_large;
  }
}
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19