Better defaults for popovers

posted on

I recently added a rule to my reset style sheet UA+ that I wanted to share with you.

When you add a popover to a page and open it, it looks similar to a dialog in terms of its styling. It's positioned at the center of the viewport.

Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser.

That's okay, but I would argue that in most cases you want your popovers aligned closely with the button that controls them. As it turns out, that's super easy to achieve in browsers that support CSS anchor positioning, since popovers already have an implicit anchor. All you need to do is overwrite the margin property and position the popover. I'm wrapping the rule in a feature query to ensure the margin isn't reset in browsers that don't support CSS anchor positioning (At the time of writing, most importantly Safari).

  @supports(position-area: end) {
    [popover] {
      margin: 0;
      position-area: end span-end;
      position-try-fallbacks: flip-inline;
    }
  }

If you're in Chrome or Firefox, you should see the popover aligned and the bottom left (or right for RTL) edge of the button.

Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser.

You can also add position-try-fallbacks: flip-inline;, as I did here, to tell the popover to try flipping its position along the inline axis if it overflows the viewport in its initial position (Thanks, Temani, for the hint).

Nice and easy, and it's a much better default.