2 min read

CSS Starting Style (@starting-style)

The @starting-style at-rule allows you to define the initial styles of an element when it is first rendered or when it transitions from display: none to a visible state. This enables entry animations for elements appearing in the DOM, which was previously difficult to achieve with CSS alone.

1. The Problem: Animating display: none

Traditionally, CSS transitions do not work when an element changes from display: none to display: block. The browser treats this as an instantaneous change, skipping the transition.

2. The Solution: @starting-style

With @starting-style, you can specify the "before" state of the element just as it is about to be rendered.

Syntax:

@starting-style {
  /* Styles to start from */
}

3. Basic Usage

To animate an element entering the DOM (e.g., a dialog, popover, or a dynamically added element):

.box {
  /* Final state */
  opacity: 1;
  transform: scale(1);
  display: block;

  /* Enable transition for display */
  transition: opacity 0.5s, transform 0.5s, display 0.5s allow-discrete;
}

/* Initial state (before entry) */
@starting-style {
  .box {
    opacity: 0;
    transform: scale(0.5);
  }
}

/* Hidden state (for exit animations) */
.box[hidden] {
  opacity: 0;
  transform: scale(0.5);
  display: none;
}

4. transition-behavior: allow-discrete

To make this work, you must also use the allow-discrete keyword in the transition property for the display property (or overlay, content-visibility). This tells the browser to flip the value of display at the start or end of the animation, rather than instantly.

transition: display 0.5s allow-discrete;

5. Use Case: Popovers and Dialogs

This is perfect for the native Popover API or <dialog> elements.

programming/css/css programming/css/transitions-and-animations programming/css/css-layers