View transition chips

Chips that fade out and rearrange using CSS View Transitions. By Una Kravets.

html #ui#animation
<div class="container">
  <div>Item One</div>
  <div>Item Two</div>
  <div>Item Three</div>
  <div>Item Four</div>
</div>

<script>
  document.querySelectorAll(".container > div").forEach((chip) => {
    chip.addEventListener("click", (e) => {
      document.startViewTransition(() => {
        e.target.remove()
      })
    })
  })
</script>

<style>
  @keyframes fade-and-scale {
    to {
      opacity: 0;
      transform: scale(0.5);
    }
  }

  ::view-transition-old(*):only-child {
    animation: fade-and-scale 0.2s ease-in forwards;
  }

  .container {
    view-transition-name: none;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 0.5rem;
    width: 300px;
    justify-content: center;

    & > div {
      view-transition-name: match-element;
      background: white;
      border: 1px solid #ddd;
      border-radius: 15px;
      padding: 0.3rem 0.4rem 0.3rem 0.7rem;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      &::after {
        content: "x";
        font-family: monospace;
        display: block;
        height: 1.5em;
        aspect-ratio: 1;
        display: grid;
        place-content: center;
        border-radius: 50%;
        background: #ededed;
      }
    }
  }

  body {
    font-family: system-ui;
    display: grid;
    place-content: center;
    height: 100vh;
    margin: 0;
  }
</style>