Sub topic 2
Nesting, Specificity, and Discrete Entry and Exit Transitions
Assume you know CSS selectors, the cascade, transitions, display: none, and basic class toggling. This chapter focuses on the cascade details that make @starting-style work.
Nesting, specificity, and source order
A starting style can be written as a top-level rule or nested inside the element’s main rule:
.card {
opacity: 1;
transition: opacity 0.3s ease;
@starting-style {
opacity: 0;
}
}The nested form keeps the entry state beside the final state. The starting declaration applies only when the element receives its first style update. The normal declaration remains the final value.
Starting styles participate in the cascade, but normal declarations take precedence over starting-style declarations. Therefore, this produces an opaque final card:
@starting-style {
.card {
opacity: 0;
}
}
.card {
opacity: 1;
}If multiple starting-style rules match, specificity still matters. If specificity is equal, later source order wins. A common mistake is placing a more specific normal rule after the starting rule and expecting the starting value to override it. Inspect the Styles and Computed panes in DevTools to see which declaration wins.
Discrete properties and `allow-discrete`
Some CSS properties have separate states rather than a continuous range. These are discrete properties. display and overlay are examples. They cannot interpolate like opacity, but CSS can delay their state change until a transition finishes.
Use allow-discrete in the transition:
.panel {
opacity: 1;
transition:
opacity 0.3s ease,
display 0.3s allow-discrete;
}
.panel.is-hidden {
display: none;
opacity: 0;
}Entry and exit with `display: none`
The @starting-style rule supplies the missing entry value:
.panel {
opacity: 1;
transition: opacity 0.3s, display 0.3s allow-discrete;
@starting-style {
opacity: 0;
}
}
.panel.is-hidden {
display: none;
opacity: 0;
}On entry, display changes from none at the beginning, then opacity animates to 1. On exit, opacity reaches 0 before display changes to none.
Top-layer elements and `overlay`
Popovers and dialogs use the top layer, which appears above ordinary page content. During an exit animation, the browser must keep the element in that layer. Transition overlay as a discrete property:
[popover] {
opacity: 0;
transition:
opacity 0.3s,
overlay 0.3s allow-discrete,
display 0.3s allow-discrete;
}
[popover]:popover-open {
opacity: 1;
}
@starting-style {
[popover]:popover-open {
opacity: 0;
}
}Without the overlay transition, closing the popover can remove it from the top layer immediately, making the exit animation invisible.
Exercise
Why can a normal rule override a starting-style declaration?
Show answer
Starting styles provide the before-change state, while normal declarations have higher cascade priority for the final state.