How much specificity do @rules have, like @keyframes and @media?
I got this question the other day. My first thought is: weird question! Specificity is about selectors, and at-rules are not selectors, so… irrelevant?
To prove that, we can use the same selector inside and outside of an at-rule and see if it seems to affect specificity.
body {
background: red;
}
@media (min-width: 1px) {
body {
background: black;
}
}
The background is black. But… is that because the media query increases the specificity? Let’s switch them around.
@media (min-width: 1px) {
body {
background: black;
}
}
body {
background: red;
}
The background is red, so nope. The red background wins here just because it is later in the stylesheet. The media query does not affect specificity.
If it feels like selectors are increasing specificity and overriding other styles with the same selector, it’s likely just because it comes later in the stylesheet.
Still, the @keyframes
in the original question got me thinking. Keyframes, of course, can influence styles. Not specificity, but it can feel like specificity if the styles end up overridden.
See this tiny example:
@keyframes winner {
100% { background: green; }
}
body {
background: red !important;
animation: winner forwards;
}
You’d think the background would be red, especially with the !important
rule there. (By the way, !important
doesn’t affect specificity; it’s a per-rule thing.) It is red in Firefox, but it’s green in Chrome. So that’s a funky thing to watch out for. (It’s been a bug since at least 2014 according to Estelle Weyl.)
The post How much specificity do @rules have, like @keyframes and @media? appeared first on CSS-Tricks.