:root {
  --n: 5; /* number of images */
  --d: 20s; /* duration */
}

.gallery {
  display: grid;
  width: 520px;
}

.gallery > img {
  grid-area: 1/1;
  width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
  border: 10px solid #f2f2f2;
  box-shadow: 0 0 4px #0007;
  z-index: 2;
  animation: 
    slide var(--d) infinite,
    z-order var(--d) infinite steps(1);
}

.gallery img:last-child {
  animation-name: slide, z-order-last;
}

/* Manually define the styles for each image based on $n = 5 */
.gallery > img:nth-child(1) {
  animation-delay: calc((1 - 1) / 5 * var(--d));
  --r: -20deg; /* Example random rotation */
}

.gallery > img:nth-child(2) {
  animation-delay: calc((1 - 2) / 5 * var(--d));
  --r: 10deg; /* Example random rotation */
}

.gallery > img:nth-child(3) {
  animation-delay: calc((1 - 3) / 5 * var(--d));
  --r: -5deg; /* Example random rotation */
}

.gallery > img:nth-child(4) {
  animation-delay: calc((1 - 4) / 5 * var(--d));
  --r: 15deg; /* Example random rotation */
}

.gallery > img:nth-child(5) {
  animation-delay: calc((1 - 5) / 5 * var(--d));
  --r: 0deg; /* Example random rotation */
}

@keyframes slide {
  10%  { transform: translateX(120%) rotate(var(--r)); }
  0%, 100%, 20% { transform: translateX(0%) rotate(var(--r)); }
}

@keyframes z-order {
  10%, 20% { z-index: 1; }
  80% { z-index: 2; }
}

@keyframes z-order-last {
  10%, 20% { z-index: 1; }
  50% { z-index: 2; }
}