brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: @starting-style gives a new element a fade-in with only CSS

Css
~/tips/tip-css-starting-style-fade-in

@starting-style {

Animates an element from a starting value when it first appears on the page.

CSS transitions don’t run when an element first appears, or when it goes from display: none to visible. There’s simply no “before” value to start from. The usual workaround was JavaScript: add the element, wait a frame, then add a class. @starting-style lets you write that “before” state in CSS, and I find it a much cleaner way to do it.

Say a toast message is added to the page and should slide up and fade in:

.toast {
  opacity: 1;
  transform: translateY(0);
  transition: opacity 0.3s, transform 0.3s;
}

@starting-style {
  .toast {
    opacity: 0;
    transform: translateY(1rem);
  }
}

When the toast is rendered for the first time, the browser takes the values in @starting-style as the starting point and transitions to the normal ones. You can also nest it inside the rule itself, which keeps everything together:

.toast {
  opacity: 1;
  transition: opacity 0.3s;

  @starting-style {
    opacity: 0;
  }
}

It works for elements added with JavaScript, for elements that switch from display: none, and for things in the top layer such as a modal <dialog>.

A few caveats from the MDN page. The starting rule has the same specificity as the normal rule, so put the standalone @starting-style block after it, or the normal values win and nothing animates. It’s only for transitions; a CSS @keyframes animation already has its own starting point and doesn’t need it. The starting values are used only on the first render: when you later remove a class, the element transitions back to its default style, not to the starting style. Animating an element out to display: none needs more work, with display in the transition list.

Support is Chrome and Edge 117, Safari 17.5 and Firefox 129. That makes it Baseline newly available since August 2024, not yet widely available. In an older browser the toast simply appears without the animation, which I think is fine for something decorative like this.

Further reading: MDN: @starting-style

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link