Transitioning Top-Layer Entries And The Display Property In CSS

Animating from and to display: none; was something we could only achieve with JavaScript to change classes or create other hacks. The reason why we couldn’t do this in CSS is explained in the new CSS Transitions Level 2 specification:

In simple terms, this means that we couldn’t start a transition on an element that is hidden or that has just been created.

What Does transition-behavior: allow-discrete Do? #

allow-discrete is a bit of a strange name for a CSS property value, right? We are going on about transitioning display: none, so why isn’t this named transition-behavior: allow-display instead? The reason is that this does a bit more than handling the CSS display property, as there are other “discrete” properties in CSS. A simple rule of thumb is that discrete properties do not transition but usually flip right away between two states. Other examples of discrete properties are visibility and mix-blend-mode. I’ll include an example of these at the end of this article.

To summarise, setting the transition-behavior property to allow-discrete allows us to tell the browser it can swap the values of a discrete property (e.g., displayvisibility, and mix-blend-mode) at the 50% mark instead of the 0% mark of a transition.

What Does @starting-style Do? #

The @starting-style rule defines the styles of an element right before it is rendered to the page. This is highly needed in combination with transition-behavior and this is why:

When an item is added to the DOM or is initially set to display: none, it needs some sort of “starting style” from which it needs to transition. To take the example further, popovers and dialog elements are added to a top layer which is a layer that is outside of your document flow, you can kind of look at it as a sibling of the <html> element in your page’s structure. Now, when opening this dialog or popover, they get created inside that top layer, so they don’t have any styles to start transitioning from, which is why we set @starting-style. Don’t worry if all of this sounds a bit confusing. The demos might make it more clearly. The important thing to know is that we can give the browser something to start the animation with since it otherwise has nothing to animate from.

A Note On Browser Support #

At the moment of writing, the transition-behavior is available in Chrome, Edge, Safari, and Firefox. It’s the same for @starting-style, but Firefox currently does not support animating from display: none. But remember that everything in this article can be perfectly used as a progressive enhancement.

Author Details

Selvakumar David

MKTG Admin

Leave a Comment