Avoiding Repetition
Consider... section.landing-page .first-dohickey {
animation: fade-in 1s;
}
section.landing-page .second-dohickey {
animation: flash-in 1s;
}
section.landing-page .third-dohickey {
animation: swirl-in 1s;
}
section:not(.landing-page):target ~ section.landing-page .first-dohickey {
animation: fade-out 1s;
}
section:not(.landing-page):target ~ section.landing-page .second-dohickey {
animation: flash-out 1s;
}
section:not(.landing-page):target ~ section.landing-page .third-dohickey {
animation: swirl-out 1s;
}
section.landing-page dohickey children when the home page for this site
is shown or hidden. (Well, there are no .*-dohickey elements on the home page, but if there
were this is how we could animate them -- see more in
Page Animations.)
Problem: That's confusing and hard to change. Imagine writing this for multiple pages
(not just the landing page), then discovering you need to change the
section:not(.landing-page):target ~ section.landing-page selector? Eugh.
Alternative: set/unset a
CSS custom property
once for the top level selector, and use it inside each of the .*-dohickey selectors.
Use two custom properties, one for indicating we should animate in, another for indicating we should animate out
unset indicates a truthy value, none indicates a falsy value.
For each .*-dohickey, coalesce the relevant variable. If it's none,
there's nothing to do because the variable is already set, and animation: none; is a noop.
If it's unset then the variable has no value, and the var function will fallback
to whatever coalesced value you provided.
(CSS Working Group spec)
section.landing-page {
--when-animating-in: unset;
--when-animating-out: none;
}
section:not(.landing-page):target ~ section.landing-page {
--when-animating-in: none;
--when-animating-out: unset;
}
.first-dohickey {
animation:
var(--when-animating-in, fade-in 1s),
var(--when-animating-out, fade-out 1s);
}
.second-dohickey {
animation:
var(--when-animating-in, flash-in 1s),
var(--when-animating-out, flash-out 1s);
}
.third-dohickey {
animation:
var(--when-animating-in, swirl-in 1s),
var(--when-animating-out, swirl-out 1s);
}
We have now separated the business of deciding when to animate in or out with the business of how to animate in or out.
See it in action
In your developer tools, search for docs_link_31919bf0 to find the relevant CSS rules running this site.