CodeBlanks Logo Icon CodeBlanks

Position-try

CSS course · Expert · Lesson 41/53

Learn collision resolution with position-try.

The collision problem

When a popover sits below its anchor and the anchor is near the bottom of the page, the popover can overflow the viewport. This is called a collision. Measuring the window edge used to need JavaScript.

position-try moves that measurement into CSS. If the default position does not fit, the browser tries the next fallback. All declarative, all automatic.

The @position-try at-rule

A fallback position is defined by the @position-try at-rule. It takes a name and a block: @position-try --flip-above { top: anchor(top); bottom: auto; }. The block states the reverse of the default position.

Here top: anchor(top) moves the element to the anchor's top edge; bottom: auto clears the bottom edge. When the fallback kicks in, the popover opens upward.

Applying fallbacks

To apply the fallbacks you list their names on the position-try property: position-try: --flip-above --flip-right;. The browser tries the default first; if it does not fit, it moves to the next fallback.

Built-in keywords exist too. Writing position-try: flip-block makes the browser flip the block direction automatically; a quick fix without writing @position-try by hand.

Exercise Define a fallback position

Write an @position-try --flip-above at-rule. The block must contain top: anchor(top) and bottom: auto. This fallback flips the popover above the anchor.

Show example solution
/* fallback position: above the anchor */
@position-try --flip-above {
  top: anchor(top);
  bottom: auto;
}

Test yourself

  1. What is position-try for?

    • It renames the anchor
    • It paints the positioned element's background
    • It tries fallback positions on collision
    • It adds a gap between anchor and element
    Show answer

    It tries fallback positions on collision — Correct. position-try tries fallback positions in order when the default does not fit the viewport.

  2. Write the @position-try name

    @position-try ____ {
      top: anchor(top);
      bottom: auto;
    }
    Show answer
    @position-try --flip-above {
      top: anchor(top);
      bottom: auto;
    }
  3. Match each property to its role

    @position-try
    Defines a fallback
    position-try
    Applies fallbacks
    anchor()
    Positions by the anchor
    position-anchor
    Binds to an anchor

All lessons in Expert