#htmx #html #frontend

Day 8: CSS Transitions

Welcome to Day 8. “SPAs feel smooth, MPAs feel clunky.”

Not anymore. htmx provides hooks for standard CSS transitions.

The htmx-swapping Class

Before swapping content, htmx adds htmx-swapping to the target. After the swap, it settles.

.fade-me-out.htmx-swapping {
  opacity: 0;
  transition: opacity 1s ease-out;
}

If you set a swap delay (in config), this allows for exit animations.

The htmx-added Class

New content gets htmx-added.

.fade-in {
  opacity: 0;
}
.fade-in.htmx-added {
  opacity: 1;
  transition: opacity 1s ease-in;
}

View Transitions API

The modern way (in newer browsers) is even easier.

<button hx-get="/page2" hx-target="body" hx-push-url="true">
    Go
</button>

In your CSS:

/* Enable view transitions */
@view-transition {
  navigation: auto;
}

htmx also has a transition:true flag in newer versions to wrap the swap in a View Transition automatically.

Challenge for Day 8

  1. Make a list of items.
  2. When you add an item, it should slide in from the left.
  3. When you delete an item, it should fade out red before vanishing.

Solution:

/* Styles */
.item { transition: all 0.5s; }
.item.htmx-swapping { opacity: 0; background: red; }
.item.htmx-added { transform: translateX(-100%); }
<button hx-delete="/item/1" hx-target="closest .item" hx-swap="outerHTML swap:1s">
   Delete
</button>

Note swap:1s. This tells htmx “Wait 1 second for the CSS animation to finish before actually removing the DOM node”.

Tomorrow: Client Side Scripting.