Unicorn Platform

World's best and simplest website builder powered by AI

Build your website
Saturday, December 2, 2023

Floating ui - a js library to position floating elements and create interactions for them

Most website owners would agree that properly positioning floating UI elements like tooltips, popovers, and menus can be tricky.

Well, the open-source Floating UI JavaScript library aims to simplify floating element positioning and interactions. It provides collision detection, automatic positioning, and framework integrations to handle these complexities for you.

In this post, you'll learn the basics of Floating UI, including its default positioning strategies, integration with popular frameworks like React, and advanced implementation tips to create polished, interactive user interfaces.

Introduction to Floating UI: Simplify Your Floating Elements

Floating UI is a lightweight JavaScript library that helps developers position floating elements on a webpage, like tooltips, popovers, and dropdown menus.

With over 12.5k stars on GitHub, Floating UI has become a popular solution for managing floating elements in web interfaces. It handles complex positioning logic behind the scenes, freeing developers to focus on building highly interactive user experiences.

Key Benefits of Using Floating UI

Here are some of the main benefits Floating UI provides:

  • Automatic collision detection - Floating UI automatically detects collisions between floating elements to prevent overlaps. This ensures menus and popovers cleanly display without blocking each other.

  • Smart coordinate calculations - The library handles offsets and alignments so elements appear precisely where needed. You can easily position tooltips relative to buttons, keep dropdowns visible inside parent containers, etc.

  • Responsive positioning - Floating elements rearrange fluidly based on available space, staying visible as the viewport size changes. This creates responsive, mobile-friendly interactions.

  • Framework agnostic - Floating UI works with any front-end framework like React, Vue, Angular, and Svelte or with plain JavaScript.

  • Tiny footprint - At around 3kB gzipped, Floating UI adds very little bloat. It's designed to be lean and fast.

In summary, Floating UI takes care of the tricky logic behind floating elements. By offloading positioning calculations to this library, developers can provide polished user experiences without complex custom code.

What is the default position of floating UI?

By default, floating UI elements are positioned at the bottom center of the reference element. This positioning makes it easy to create common UI patterns like tooltips and popovers that emerge from another element on the page.

Some key things to know about the default positioning behavior:

The element is centered horizontally

The floating UI will line up centered with the middle of the reference element horizontally. This avoids the interface appearing off to one side and looking awkward.

Stacks vertically below by default

Instead of appearing right on top and covering the reference, floating UIs render below vertically. The slight gap also indicates that focus has shifted to this new interface emerging on screen.

Adjustments occur automatically

If the default position would send the floating UI off-screen or into an unusable location, logic automatically adjusts it to keep the content visible. This avoids frustration and clipped or hard-to-access content.

Easy customization where needed

While the out of box positioning works for most use cases, everything can be configured and tweaked as needed. You have full control to make the floating UI match your desired design.

So in summary - centering with default bottom emergence facilitates common patterns like tooltips. But complete flexibility exists to override defaults and position however needed for a given page layout.

What is the position of useFloating?

useFloating() is the core hook in @floating-ui that handles positioning floating elements like tooltips and popovers.

By default, it positions the floating element at the bottom-center of its reference element. However, the position can be customized by providing different placement options like top-start, left-end etc.

Here is a quick example to position a Tooltip at the top of a Button using useFloating():

import { useFloating } from '@floating-ui/react-dom-interactions';

function Tooltip() {
  const { x, y, reference, floating, update } = useFloating({
    placement: 'top',
  });
  
  return (
    <>
      <button ref={reference}>Reference</button>  
      <div ref={floating} style={{ position: 'absolute', top: y ?? '', left: x ?? '' }}>
        <TooltipContent/> 
      </div>
    </>
  );
}

This handles all the positioning logic behind the scenes. The key things to note are:

  • The placement option defines the position of the floating element relative to the reference element.

  • The reference and floating refs need to be attached to the appropriate elements.

  • The x and y positions are applied to the floating element to position it.

So in summary, useFloating() abstracts away all the complexity behind positioning floating components in an accessible way. It's the foundation that powers all of Floating UI.

Where is the popover position in floating UI?

Floating UI is a JavaScript library that helps position floating elements, like tooltips, popovers, and dropdowns. It uses smart positioning logic to anchor these elements to their reference element on the page.

When it comes to popovers specifically, Floating UI positions them right next to the reference element, so they feel connected. As you scroll or resize the page, the popover stays anchored. This helps avoid frustrating jumps as things move around.

Floating UI handles popover positioning in a few key ways:

  • Dynamic Anchor Positioning: The popover remains anchored to the side of the reference element, adapting position to avoid clipping offscreen or covering other elements.

  • Toggle on Click: Clicking the reference element opens and closes the popover, like a toggle. This provides an intuitive interaction model.

  • Dismissal Handling: If the user presses ESC or clicks outside the popover, it dismisses. This prevents popovers staying open accidentally.

By handling these key pieces of popover UX, Floating UI makes positioning them much easier compared to doing it manually. The popovers feel connected, avoid intrusive overlaps, and handle open/close behavior automatically.

This smart positioning system works well for all sorts of use cases like dropdowns, selects, tooltips, and contextual overlays. By taking care of the positioning logic, you can focus on building the actual content and interactions.

Overall, Floating UI's popover positioning creates a smooth, modern experience for users. The popovers feel responsive and connected, yet get out of the way when needed. This helps elevate interactivity and usability on sites.

What is the fixed strategy of floating UI?

The fixed strategy in floating UI is used to position floating elements in a way that breaks them out of their parent clipping context. This allows the floating element to remain in the normal document flow while being positioned independently.

Some key things to know about the fixed strategy:

  • It works by applying position: fixed to the floating element. This makes it positioning relative to the viewport rather than its parent container.

  • Using fixed will prevent layout issues from the floating element being removed from flow. It keeps the DOM structure intact.

  • Elements under a fixed element will still respect its space as if it were still in normal flow. This prevents content from jumping around.

  • There are some cases where fixed positioning might cause clipping by ancestor elements with overflow: hidden. But it works well in most situations.

  • Fixed positioning relies on JavaScript to calculate positions rather than CSS. This allows greater flexibility in logic when positioning elements.

In summary, the fixed strategy is useful for keeping floating UI in place relative to the viewport while maintaining its place in the DOM layout. This helps prevent common issues with elements moving around unexpectedly.

sbb-itb-b5a6996

Diving into Floating UI/Core

To use Floating UI effectively, you need to understand positioning, detecting collisions, managing visibility, and handling user interactions.

Mastering Element Positioning with Floating UI/Core

Floating UI utilizes Popper.js under the hood to position elements relative to a reference element. It offers a wide range of options to control positioning:

  • Offsets to shift the floating element's position by a set amount horizontally and/or vertically
  • Powerful alignments like top, right, bottom, left to anchor the element
  • Flexible middleware to modify positions at runtime
  • Auto-placements to automatically adjust positioning based on viewport collisions

This makes it easy to show tooltips, dropdowns, popovers and other floating components in the ideal spots to fit your UI design needs.

For example, you can set a popover to render 10px below and centered horizontally to a button. And if that causes a collision, the auto placements can shift it into view nearby instead.

Collision Detection Strategies with Floating-ui/dom

The collision detection utility checks if a floating element intersects any other elements on the page, like the viewport edges. This knowledge allows properly controlling visibility.

Useful detection strategies include:

  • Viewport detection - check if an element overflows past the viewport edges
  • Scroll detection - check if an element is visible based on scroll position
  • Element detection - check if an element intersects specific elements

So you can detect when a dropdown goes out of view during scroll, and hide it to prevent awkward UI.

Managing Visibility and Z-Index

Floating UI offers hooks to manually show or hide floating elements based on certain events:

  • Scroll position
  • Window resizes
  • Collision detection
  • User interactions

It also includes utilities to manage the z-index of components, ensuring proper stacking order.

For example, you can set a rule to hide a persistent sidebar on mobile widths. And make sure tooltips always show above other elements.

Floating UI/React Example: Handling User Interactions

The library provides utilities to respond to user events like hover, focus and click.

This allows showing or hiding floating components based on user interactions for a smooth experience:

  • Show a tooltip on button hover
  • Toggle a dropdown menu on click
  • Display a popover on focus
  • And more...

In this Floating ui/react example, we use the useFloating hook to show/hide a popover based on the focus state of an input:

import { useFloating } from '@floating-ui/react-dom-interactions';

function App() {
  const { x, y, reference, floating, strategy } = useFloating({
    open: focused,
    onOpenChange: setFocused
  });

  return (
    <>
      <input ref={reference} onFocus={() => setFocused(true)}/> 

      <div ref={floating}>
        I am a popover  
      </div>
    </>
  );
}

This allows easily building complex floating interactions in React with just a few lines of code!

Crafting UI Components with Floating-ui/npm

Dive into the major UI components Floating UI offers out-of-the-box for common floating interface needs, all available through the Floating-ui/npm package.

Designing Tooltips with Floating UI: A Tooltip Example

Floating UI includes robust tooltip positioning, collision detection, and styling options to display helpful information on hover/focus, as shown in the Floating ui tooltip example.

The floating-ui library provides an easy way to position tooltips relative to a reference element. Some key features include:

  • Automatic positioning based on available space around the reference element
  • Collision detection to avoid tooltips overflowing the viewport boundary
  • Options to offset tooltips along x and y axes for fine tuning
  • Support for hover, focus and click events to show/hide tooltips
  • Can customize tooltip styling as needed

Here is an example React implementation:

import { useFloating } from '@floating-ui/react-dom';

function Tooltip({ content }) {
  const { x, y, reference, floating, strategy } = useFloating({
    placement: 'top',
    middleware: [offset(5)],  
  });
  
  return (
    <Floating>
      <div ref={reference}>
        <button>Reference</button>  
      </div>
      <div
        ref={floating}
        style={{
          position: strategy,
          top: y ?? '',
          left: x ?? '',  
        }}
      >
        {content}
      </div>
    </Floating>
  );
}

This shows the core API for positioning a basic tooltip component. The library handles collisions automatically within the viewport.

Creating Dynamic Popovers with Floating UI/Popover

Popovers are similar to tooltips but allow more content. Floating UI handles positioning popovers relative to a trigger element, which can be implemented following the Floating ui popover guidelines.

The @floating-ui/react-dom package includes a usePopup hook to handle popover logic:

  • Set popover position based on trigger element
  • Toggle visibility on click/hover
  • Collision detection
  • Customizable styling

A popover usage example:

import { usePopup } from '@floating-ui/react-dom';

function Popover() {

  const { x, y, reference, floating, isOpen, update } = usePopup();

  return (
    <>
      <button ref={reference}>Trigger</button>
      
      {isOpen && (
        <div
          ref={floating}
          style={{
            position: 'absolute',
            top: y ?? '',
            left: x ?? ''  
          }}  
        >
          // popover content
        </div>
      )}
    </>
  );
}

The key benefit is it handles positioning logic out-of-the-box.

The library provides support for positioning dropdown menus connected to trigger buttons with collision detection.

A React dropdown example using useDropdown:

import { useDropdown } from '@floating-ui/react-dom';

function Dropdown() {

  const { x, y, reference, floating, isOpen, update } = useDropdown();

  return (
    <>
      <button ref={reference}>Open Menu</button>

      {isOpen && (
        <ul
          ref={floating}
          style={{
            position: 'absolute',
            top: y,
            left: x
          }}
        >
          <li>Option 1</li>
          <li>Option 2</li>
        </ul>  
      )}
    </>
  );
}

The dropdown handles viewport collisions, making implementation straightforward.

Enhancing React Components with @floating-ui/react-dom-interactions

This package has React hooks for user interactions like hover, focus and click events to easily control showing/hiding of floating components.

The useHover hook allows showing a tooltip on hover:

import { useHover } from '@floating-ui/react-dom-interactions';

function Tooltip() {

  const { hovered, reference, floating } = useHover();

  return (
    <>
      <button ref={reference}>Reference</button>

      {hovered && (
        <div ref={floating}>
          Hovered tooltip! 
        </div>
      )}
    </>
  );
}

And useClick toggles component visibility on click. These interactions pair nicely with the positioning hooks.

Seamless Framework Integration with Floating UI

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis luctus nisl, ut volutpat ex condimentum vel. Curabitur at nisl vehicula, elementum lorem sed, blandit justo. Morbi volutpat elementum lacus eu varius. Aliquam erat volutpat. Praesent pulvinar risus vitae turpis convallis mattis. Integer et fringilla enim. Donec sit amet porttitor tortor.

Floating UI in Action: React Integration and Examples

Sed ac mollis massa, nec condimentum diam. Mauris a iaculis velit. Vivamus tempor ultrices est, sit amet sollicitudin turpis dictum id. Ut non felis id nisl convallis tempus. Fusce pellentesque neque in neque commodo ultrices. Donec orci nulla, pharetra ac elementum quis, fermentum vitae tortor.

Aliquam erat volutpat. Pellentesque ac pellentesque mi. Aenean sed ligula dignissim, condimentum tortor fermentum, suscipit diam. Integer finibus neque aliquam mattis bibendum. Nunc porttitor tortor non mattis bibendum.

Expanding to Vue and Angular

Donec eget auctor tortor, quis finibus augue. Etiam ultricies augue a felis porttitor tincidunt. Cras vel dui id ligula finibus condimentum nec id orci. Sed ac vehicula lorem, et dignissim libero. Integer porta semper nisl, a imperdiet dolor rhoncus commodo. Sed suscipit tempor cursus.

Community Framework Contributions

Nam id commodo lorem. Cras ac nisl vel eros finibus pellentesque. Aenean pharetra, enim eget auctor auctor, enim nisi tempus ipsum, quis iaculis urna quam ut mi. Phasellus condimentum quam eget lectus venenatis fringilla. Pellentesque porttitor elit in vulputate sagittis. Nunc ut tempus orci, eu dignissim elit.

Advanced Tips for Floating UI Implementation

Follow these best practices when leveraging Floating UI in your projects for optimal results.

Strategic Z-Index Management in Floating UI

Use the middleware options in Floating UI to manage z-indexes between floating elements to control overlap.

For example, you can set the zIndex property on the options object passed to floatingUI.create to ensure your tooltips or popovers appear above other elements:

floatingUI.create({
  // Other options
  zIndex: 10,
});

You can also use the applyZIndex middleware to apply a higher zIndex value programmatically:

import { applyZIndex } from "@floating-ui/react-dom-interactions";

floatingUI.create({
  middleware: [applyZIndex(10)],
}); 

This helps prevent floating elements from getting hidden behind layout content.

Optimizing Performance for Smooth Interactions

Limit collision detection to visible area and throttle events to ensure buttery smooth animations on scroll or resize.

By default, Floating UI checks the entire document for collisions which can hurt performance. Set the strategy option to only check collisions in the current scroll container:

floatingUI.create({
  strategy: "fixed", 
});

You can also throttle scroll and resize events with throttle.leading to limit how often they get fired:

import { throttle } from "@floating-ui/dom";

function handleThrottle() {
  // Animation logic
}

window.addEventListener(
  "scroll", 
  throttle.leading(handleThrottle, 100)
);

This maintains smooth animations even when rapidly scrolling or resizing.

Custom Styling for Unique UI Elements

Floating UI handles positioning and behavior, but does not style elements. Add your own CSS for tooltips, dropdowns etc.

For example, to create a custom tooltip:

/* Tooltip.js */

import { useFloating } from "@floating-ui/react-dom-interactions";

export default function Tooltip() {

  const { x, y, reference, floating, strategy } = useFloating({
    middleware: [offset(5)],  
  });
  
  return (
    <div ref={reference}>
      <div 
        ref={floating}
        className="bg-black text-white p-2 rounded shadow"
        style={{
          position: strategy,
          left: x ?? '',
          top: y ?? '',  
        }}
      >
        Custom tooltip!
      </div>
    </div>
  );
}

Then import and use this anywhere:

import Tooltip from "./Tooltip";

function App() {
  return (
    <Tooltip>Hover me!</Tooltip>
  );
}

This allows full control over styles while leveraging Floating UI's positioning.

Wrapping Up: The Floating UI Essentials

The Floating UI library provides developers with powerful tools to create robust and interactive floating user interfaces. With its intuitive API and wide range of capabilities, Floating UI simplifies complex tasks like element positioning, collision detection, viewport awareness, and framework integrations.

Some key things to remember about Floating UI:

  • It uses smart positioning algorithms to automatically place floating elements in ideal spots relative to references like anchors, containers, viewports etc. This prevents overlapping and keeps things cleanly laid out.

  • Collision detection ensures your floating UIs never end up hidden or clipped by other page elements. Floating UI continuously tracks collisions and repositions accordingly.

  • Integrations with popular frameworks like React, Vue and Svelte make it seamless to leverage Floating UI's features in your projects. The syntax feels natural thanks to reactive bindings, composable behavior etc.

  • Options like auto-hiding, transitions, bounding boxes and more provide extensive control over floating UI behavior. You can craft slick, smooth and responsive experiences.

In summary, Floating UI is an indispensable tool for crafting modern floating interfaces. Its robust feature set and elegant API abstract away layout complexities so you can focus on building creative user experiences. Give it a spin in your next project!