I'm experimenting with the new Popover API and trying to make a dropdown with it.
I have a button to open my dropdown menu, the dropdown menu itself, and I'm struggling to position my dropdown menu correctly. I want to place it directly below the button. I've tried position: absolute on my dropdown and position: relative on a parent div, but it does not seem to help.
Hello world
<div style="position: relative">
<button popovertarget="dropdown">Open Dropdown</button>
<div popover id="dropdown" style="position: absolute; top: 20px">
<ul>
<li>Menu Item 1</li>
<li>Menu Item 2</li>
</ul>
</div>
</div>
As you can see, the popover appears in the center of the screen. Is it possible to position a popover relative to another element?
CSS anchor positioning will (hopefully soon) be the ideal way to achieve this:
Certain elements are defined as anchor elements; anchor-positioned elements can then have their size and position set based on the size and location of the anchor elements to which they are bound.
But unfortunately as of writing it's only supported in Chromium.
For now the best approach is still to work out the position of the dropdown and position it using javascript. The popover API is still helpful since it breaks out of the z-stack, avoiding the need for things like portals in React.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With