Elastic/Stretching UI With CSS Anchors

Opposing insets, like using both left: 0 and right: 0, usually force positioned elements to fill their container or viewport. Add CSS anchors to the equation, and we’ve got ourselves stretchy/elastic elements that dynamically stretch between their anchors.

It creates a visual effect, say for when a selection indicator goes from one item to another.

Like these:

Example 1) A Stretchy Toggle

Let’s start with the simple one: the dark/light toggle. It’s a couple of radio buttons with the same name, kept in a list. There’s also the indicator, the one that stretches, in the list.

The indicator can be placed anywhere. I just want to keep the related markup together.

<menu id="toggleCtl">
  <li>
    <div id="toggleIndicator"></div>
  </li>
  <li>
    <input type="radio" name="r" id="darkRb" checked>
    <label for="darkRb">Dark</label>
  </li>
  <li>
    <input type="radio" name="r" id="lightRb">
    <label for="lightRb">Light</label>
  </li>
</menu>Code language: HTML, XML (xml)

Anchoring

We’re now going to turn the indicator into an anchored element, which is simple: give it the position value absolute or fixed and then attach it to an anchor.

#toggleIndicator {
  position: absolute;
}Code language: CSS (css)

The indicator should anchor to either the dark or light option. We apply an anchor name to whichever one is currently selected.

li:has(:checked) {
  anchor-name: --chosenAnc;
}Code language: CSS (css)

Next, we link the indicator to --chosenAnc by declaring inset with an anchor() value, both making the connection and stretching the indicator to be the same dimension as its anchor.

#toggleIndicator {
  position: absolute;
  inset: anchor(--chosenAnc inside);
  /* The above translates to
     top    = anchor(--chosenAnc top)
     left   = anchor(--chosenAnc left)
     bottom = anchor(--chosenAnc bottom)
     right  = anchor(--chosenAnc right)
  */
}Code language: CSS (css)

Now whichever option is selected, the indicator goes to it and its edges align with those of its anchor.

Animation

To animate that movement and create the elastic effect, we apply a transition that targets the indicator’s left or right sides with different delays based on the selection.

Here’s why we target the sides to create the stretchiness: moving one edge first stretches the element, then a moment later we move the opposite edge, shrinking the element back to the original size.

#toggleIndicator {
  /* ... */
  transition-time: 0.6s; 
  transition-delay: 0.6s, 0s, 0s;
}
/* When light is chosen */
#toggleCtl:has(#lightRb:checked) #toggleIndicator { 
  background:  beige;
  transition-property: left, right, background-color;
}
/* When dark is chosen */
#toggleCtl:has(#darkRb:checked) #toggleIndicator { 
  background:  lightgrey;
  transition-property: right, left, background-color;
}Code language: CSS (css)

When the indicator goes from dark to light (left to right), the left side gets a delay of 0.6s. Going the other way, the right side gets the delay.

Example 2) A Stretchy Active Nav Indicator

The above example showed two options. We knew which one was the anchor at a given time and the direction to move the indicator towards when the selection changes. Let’s do the same thing, but with more than two options.

This time the new option could be in any direction, so we handle this a little differently.

<menu>
  <li>
    <div id="indicator"></div>
  <li>
    <input type="radio" name="r" id="r1" checked>
    <label for="r1">Home</label>
  <li>
    <input type="radio" name="r" id="r2">
    <label for="r2">Pay</label>
  <li>
    <input type="radio" name="r" id="r3">
    <label for="r3">Cards</label>
  <li>
    <input type="radio" name="r" id="r5">
    <label for="r5">Services</label>
</menu>Code language: HTML, XML (xml)

Track Selection

The first thing we do is make sure we know, along with the currently selected option, which one was previously chosen. We use JavaScript to apply a class name to the last chosen element.

let prev = document.querySelector('li:has(:checked)'), prior;
document.querySelector('menu').addEventListener('change', e => {
  // Remove 'prev' from the item selected two steps ago
  prior?.classList.remove('prev');
  // Add 'prev' to the item selected one step ago
  prev?.classList.add('prev');
  // 'prior' becomes the old 'prev', and 'prev' becomes the current item
  [prior, prev] = [prev, e.target.closest('li')];
});Code language: JavaScript (javascript)

The code saves the currently selected item to prev. When a new selection is made, if there’s a previous one (prev already exists), it gets the class name 'prev'.

This way, it tracks the previously chosen item by transferring the class name each time.

Anchoring

#indicator {
  position: absolute;
  inset: min(anchor(--currAnc inside), anchor(--prevAnc inside));
  transition: inset 0.6s;
}Code language: CSS (css)

Same as the first example, the indicator is the anchored element, positioned absolute.

Its inset values, however, are made up of one of two or both of the anchors’ edges, depending on the current and the previously selected items.

Like I mentioned before, we don’t know which side the newly chosen item is going to be on relative to the previous one. By using min(), we make sure the closest inset edges of both the anchors are considered when the indicator relocates from the old one to the new. We’ll see in a moment how this affects the result.

Animation

Since we can’t tell if the left or right edge of the indicator needs to move first, we apply animations to the anchors instead.

When a new item is selected, it gets the --currAnc anchor name and the previous one gets --prevAnc right away.

A moment later, the current one gets both --prevAnc and --currAnc, and the previous one gets none.

/* Current chosen item */
li:has(:checked) {
  animation: 0.3s setCurrAnc forwards steps(1);
}
/* Previously chosen item */
.prev { /* class 'prev' is added by JS */
  animation: 0.3s setPrevAnc forwards steps(1);
}
@keyframes setCurrAnc {
  0%    { anchor-name: --currAnc; }
  100%  { anchor-name: --prevAnc, --currAnc; }
}
@keyframes setPrevAnc {
  0%    { anchor-name: --prevAnc; }
  100%  { anchor-name: none; }
}Code language: CSS (css)

Now, whichever item is chosen, the indicator moves to it.

Say the previously selected item is on the left (where the indicator also is) and the current one is on the right.

The indicator’s right edge goes to the current anchor’s right edge (the closest right edge to the container’s right edge) while its left edge remains where it is on the previous anchor (the closest left edge to the container’s left edge).

At the end of the animation, the indicator’s left edge, too, then goes to the current one since it now has both the anchor names: --prevAnc, --currAnc.

The key to the stretchy effect is to either pull the anchored element between different anchors in opposite directions or simply animate the opposite edges with different timings.

Since an anchored element is also by default a positioned element (absolute or fixed), it expands to the edges we anchor it to, producing the stretchy effect.

Leave a Reply

Your email address will not be published. Required fields are marked *

$966,000

Master.dev donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.