@floating-ui
Most website owners would agree:
It's challenging to create intuitive, responsive UI elements like floating tooltips and popovers.
But what if you could build highly interactive, cross-platform floating UIs with just one library?
The new @floating-ui framework makes it surprisingly easy.
In this post, you'll discover how @floating-ui helps you craft precision floating UIs with native-quality performance. We'll cover key capabilities like automatic positioning, framework integration, animation, and accessibility support. You'll also find real-world examples and code samples to help you integrate @floating-ui into your next web project.
Introducing @floating-ui - A Powerful UI Library for Creating Floating Elements
@floating-ui is an open-source JavaScript library that enables developers to easily create floating UI elements like popovers, tooltips, and dropdown menus.
This robust library provides a flexible API for controlling the positioning and visibility of floating components. Some key benefits of @floating-ui include:
- Intuitive API: The API is intuitive and easy to use. You can precisely position elements relative to other elements on the page.
- Lightweight: @floating-ui is lightweight, with no dependencies, making it easy to integrate into any project.
- Framework Agnostic: It works with any JavaScript framework like React, Vue, Angular etc.
- Responsive: Floating elements respond smoothly to viewport changes and element resizes.
- Accessible: Follows accessibility best practices to support keyboard and screen reader users.
- Customizable: Highly themeable and customizable with CSS to match your brand.
Overall, @floating-ui solves the complexities around building well-positioned and responsive floating UI elements. If you're looking to easily add beautiful tooltips, popovers or dropdowns in your app, @floating-ui is definitely worth checking out!
What is a floating UI?
A floating UI refers to user interface elements that appear to float over other content on a webpage. Some common examples of floating UI elements include tooltips, popovers, dropdown menus, and dialog boxes.
Floating UIs are useful because they allow supplementary content and controls to be accessible without taking up permanent space on the screen. They appear when needed and can be dismissed when no longer required.
The floating-ui library provides primitives to help developers build various floating UI components in a flexible and extensible way. Some key capabilities it offers:
- Positioning elements next to a reference element, e.g. showing a tooltip above an icon
- Support for different view layers like the web, React, React Native, Canvas etc.
- Calculations for collision detection, viewport awareness etc. to handle complex UI behaviors
- APIs for creating interactive elements like tooltips and popovers
In summary, floating-ui makes it easier to implement floating UIs that feel natural and respond smoothly to user actions. Developers can use the low-level building blocks to construct floating elements tailored to their specific needs.
The library is designed to be lightweight, dependency-free and work across various platforms. This makes it well-suited for adding dynamic and responsive overlays to enhance modern web and mobile experiences.
What is the difference between popper and floating UI?
Floating UI and Popper.js are both JavaScript libraries used for positioning floating elements on web pages. However, there are some key differences:
Floating UI is built with TypeScript, while Popper uses Flow. This means Float UI provides:
- Better type checking and readability
- Strictly typed modifiers that are predictable
- Overall more robustness
In contrast, Popper has loose typing by default, meaning modifiers are not as strictly checked.
Additionally, Floating UI was designed from the ground up to be lightweight and have a simple API. It aims to solve the problem of positioning elements in the most straightforward way.
Popper.js on the other hand is more fully-featured and complex. It has many more options and customization available out of the box.
In summary:
- Floating UI is lighter weight, simpler, and leverages TypeScript
- Popper.js has more built-in features and options, but is more complex
So in most cases if you just need basic floating element positioning, Floating UI is a great choice. But if you need richer functionality like animated transitions, collision detection, and advanced customization, Popper may be better suited.
The best approach is to evaluate both libraries against your specific use case requirements. But for many basic uses, Floating UI delivers robust positioning with a simpler and more lightweight API.
What is the default position of floating UI?
By default, floating-ui positions popovers, tooltips, and other floating elements at the bottom-center
of their reference element. This means the floating element will be centered horizontally below the reference element.
Some key things to know about the default positioning:
- The default
strategy
isfixed
, meaning the floating element is positioned relative to the viewport rather than scrolling with the page. This allows the element to remain visible even when scrolling. - The default
placement
isbottom-center
as mentioned. This can be changed to any of the other placements liketop-start
,left-end
, etc. - Sensible
offsets
andconstraints
are applied automatically to keep the floating element visible in view. For example, it will flip to the top if there isn't enough space below. - The defaults provide a good starting point, but can be customized as needed for any use case.
So in summary, bottom-center
with dynamic repositioning behavior is the default floating position in floating-ui. This sets a solid foundation while allowing the flexibility to tweak positions and behavior as required.
Knowing these defaults allows you to quickly implement floating elements without worrying much about positioning details. But floating-ui also gives you full control when you need it.
Where is the popover position in floating UI?
Floating UI handles popover positioning dynamically to provide the best user experience. When a popover is triggered, floating UI calculates the optimal placement next to its reference element while avoiding on-screen collisions.
Some key points about floating UI's popover positioning:
- The popover remains anchored to the reference element, even if it moves on-screen. This keeps the context for the user.
- Collision detection avoids overlapped UI and prevents popovers from being cut off screen. Positions are flipped automatically (e.g. bottom to top) if needed.
- Click events on the reference element toggle the popover open and closed.
- Pressing ESC or clicking outside the popover while open will dismiss it.
This smart positioning system allows popovers to feel natural as part of the UI flow. Developers can leverage it easily with minimal positioning code.
By handling overlaps and viewport collisions automatically, floating UI takes care of frustrating popover issues out-of-the-box. The popovers feel reliably positioned near their triggers.
For more details on configuring floating UI popovers, check out the documentation. Options are available to fine-tune behavior as needed.
Key Benefits of Using @floating-ui
@floating-ui makes it simple to build sites with advanced UI interactions, improving user experience for modern web projects.
Intuitive Floating UI Positioning
The library includes a smart auto-placement system that will automatically position floating elements near their triggers in an intuitive way. Some key benefits include:
- The positioning engine detects viewport edges and collision boundaries to place elements in the optimal spot that feels natural to users.
- Options like
autoPlacement
andplacementPriority
give fine-grained control over positioning logic. - Methods like
computePosition()
,flip()
, andshift()
make it easy to manually adjust positions.
With just a few lines of code, you can create complex floating UIs like dropdowns, tooltips, and popovers that feel polished.
Cross-Framework Compatibility
@floating-ui contains framework-agnostic utilities that work with React, Vue, Angular and more. There are also officially supported wrappers for popular frameworks like:
This means you can use the robust positioning engine in virtually any modern web project.
The library is even compatible is environments like React Native, to build mobile UIs. Cross-framework support helps teams standardize on @floating-ui while retaining flexibility.
Responsive and Adaptive UI
Floating elements created with @floating-ui automatically adapt their position based on viewport size changes to ensure they remain visible.
As you resize the window or viewport, tooltips, dropdowns, and other elements smoothly transition to new optimal positions, rather than awkwardly overlapping content.
This helps create interfaces that look polished regardless of device size. Features like strategy
and middleware
give fine control over how floating elements behave responsively.
Enhanced Development with TypeScript
The library is written in TypeScript, providing helpful typings and autocomplete to speed up development.
For example, methods like computePosition()
and options like placement
are fully typed. This catches errors during coding rather than at runtime.
Type definitions also enable auto-complete in code editors like VS Code, letting you quickly reference available options without needing to check docs. This streamlines building complex floating UIs.
Lightweight and Efficient
@floating-ui has no dependencies and a small footprint, adding minimal bloat to projects.
It uses efficient algorithms and logic to compute positioning rather than DOM measurements. This allows buttery smooth animations for elements entering and leaving the page.
The library is also tree-shakeable, so you only include the features actually used in your project. This helps optimize bundle size for production.
Overall, @floating-ui is designed be lightweight yet robust for seamlessly enhancing interactivity.
sbb-itb-b5a6996
Seamless Integration with Web Frameworks
@floating-ui integrates nicely with popular frontend frameworks like React, Vue and Angular. Let's explore some examples.
Floating-ui/react-dom: Elevating React UIs
The `@floating-ui/react-dom` package wraps the core `@floating-ui` library with React bindings and components like ``.
Some key benefits include:
- Easy to add tooltips, popovers, dropdowns and other floating UIs in React apps
- Automatically handles intelligent positioning and viewport detection
- Dropdown and tooltip components for faster development
- Supports React 17+
For example, to display a basic tooltip on hover:
import { FloatingPortal, useFloating } from '@floating-ui/react-dom';
function Tooltip() {
const { x, y, reference, floating, strategy } = useFloating({
placement: 'top',
});
return (
<FloatingPortal>
<div ref={reference}>Trigger</div>
<FloatingContainer style={{ position: strategy, top: y ?? '', left: x ?? '' }}>
<div ref={floating}>
Tooltip contents
</div>
</FloatingContainer>
</FloatingPortal>
);
}
The components like `` handle all the complex logic behind the scenes.
Creating Interactive Tooltips with Floating ui/react tooltip
The React integration makes it simple to build custom popovers, tooltips and other floating UIs that correctly handle positioning and viewport detection.
The `@floating-ui/react-dom` package includes a `` component that can be used out-of-the-box:
import { Tooltip } from '@floating-ui/react-dom';
function App() {
return (
<Tooltip content="Custom tooltip">
<button>Hover me!</button>
</Tooltip>
);
}
We can customize the placement, offsets, arrow rendering and more:
<Tooltip
content="A tooltip with arrow"
placement="top"
arrow
offset={8}
>
</Tooltip>
This abstracts away manually calculating positions and focus management logic.
Embracing the Ecosystem with ngx-floating-ui and Floating-ui Svelte
While React is fully supported, @floating-ui also works with Vue and Angular when using the core positioning and visibility detection utilities. It also integrates with Svelte and provides an Angular directive via ngx-floating-ui
.
For example, to display a tooltip in Svelte:
import { createFloatingUI } from '@floating-ui/svelte';
const { x, y, reference, floating, strategy } = createFloatingUI({
placement: 'top'
});
Then apply the calculated positioning:
<div
use:reference
>Hover me
</div>
<div
style:top={y}
style:left={x}
style:position={strategy}
use:floating>
Tooltip content
</div>
So while React has first-class support, @floating-ui remains framework-agnostic and easily integrates across the JavaScript ecosystem.
Advanced Usage Concepts and Examples
Now that we've covered the basics, let's explore some more advanced concepts for tailoring @floating-ui to specific use cases.
Mastering Floating ui Position with Custom Controls
The placements API allows granular control over where floating elements can be positioned, letting you restrict visibility to certain parts of the viewport.
You can define a strategy
like 'fixed'
to enable fixed positioning relative to the viewport instead of scrolling with the page. There's also an allowOverlap
option to permit content overlap if space is constrained.
Use the modifiers
prop for extremely advanced positioning rules:
modifiers={[
{
name: 'flip',
options: {
padding: 10
}
},
{
name: 'preventOverflow',
options: {
altAxis: true
}
}
]}
This flips placement axes first before applying viewport boundary padding. The altAxis
modifier prevents overflow on the cross axis.
So in summary:
strategy
- Global positioning strategyallowOverlap
- Allow content overlap if constrainedmodifiers
- Fine-grained placement logic
With full control over placements, you can create complex floating UIs tailored to unique layout needs.
Building Scroll-Aware Interfaces
@floating-ui detects scrolling and viewport changes out-of-the-box, but also includes utilities like `` for disabling this when needed.
For example, to fix a tooltip in place while scrolling:
import {useFloating, useScroll} from '@floating-ui/react'
function Tooltip() {
const {x, y, reference, floating, strategy} = useFloating()
const scroll = useScroll()
return (
<>
<button ref={reference}>
Toggle Tooltip
</button>
<FloatingPortal>
<div
ref={floating}
style={{
position: strategy,
top: y ?? '',
left: x ?? '',
width: 'max-content'
}}
>
<TooltipContent/>
</div>
</FloatingPortal>
</>
)
}
We pass the scroll state to useFloating
which prevents the tooltip from tracking page scroll position.
Other key benefits:
- Disable auto-hiding on scroll
- Simplify logic in complex interfaces
- Build custom scroll containers
Fine-tune scroll behavior with useScroll
for the best experience.
Animating Floating Elements for Enhanced User Experience
It's easy to animate @floating-ui components on open/close using CSS or animation libraries like Framer Motion.
For example, this tooltip fades in on hover:
const tooltip = useRef()
const { x, y, reference, floating, strategy } = useFloating({
middleware: [fade({ show: true })]
})
return (
<>
<div ref={reference}>Hover me</div>
<div
ref={floating}
style={{
opacity: 0,
transition: 'opacity 200ms ease-in-out',
...
}}
>
Tooltip info
</div>
</>
)
We use a fade
middleware to animate the opacity when visible. This works automatically with no extra code!
Other options:
- CSS transitions for transforms, shadows, etc
- Framer Motion, React Spring
- Custom React animations
This takes floating UIs to the next level for modern, animated interfaces users love.
Ensuring Accessibility in Multilingual Layouts
The auto-placement positioning engine handles RTL layouts automatically, making @floating-ui a great choice for global sites.
It detects the text direction using getBoundingClientRect()
then flips placements accordingly:
function RTLTooltip({children}) {
const {x, y, reference, floating, strategy} = useFloating()
return (
<>
<div ref={reference}>Hover me</div>
<div
ref={floating}
style={{
top: y,
left: x,
position: strategy
}}
>
{children}
</div>
</>
)
}
No code changes needed! Features:
- Automatic RTL placement flipping
- Multilingual support out-of-the-box
- Consistent cross-browser behavior
- Compliant contrast ratios
This means developers can focus on translation without layout concerns.
Practical Implementation with @floating-ui
@floating-ui is a useful JavaScript library that makes it easy to add responsive, accessible floating user interfaces like tooltips, popovers, and dropdowns to web projects.
Framework-Specific Packages: Floating-ui/react-dom and Others
To use @floating-ui, first install the appropriate package for your framework - whether that's floating-ui/react-dom
for React, floating-ui/svelte
for Svelte, or plain @floating-ui/dom
for vanilla JavaScript. These provide framework-specific components and hooks while sharing the same robust positioning engine under the hood.
For example, React developers would run:
npm install @floating-ui/react-dom
Then import the useFloating
hook to handle visibility and positioning.
Discovering Real-World Examples with Floating ui/react example
The project website contains tons of sample code snippets for building features like tooltips, dropdowns, hover cards and more with @floating-ui.
Browsing these examples is a great way to understand real-world usage and see how the interactive components can be styled. For instance, this tooltip demo demonstrates adding a tooltip that follows the mouse movement using React and automatic positioning.
Diving Deep into the API Reference
To leverage @floating-ui's full capabilities, it pays to get familiar with the extensive JavaScript API docs. This covers methods for controlling floating UI visibility, automatic and manual positioning, alignments, offsets, boundaries, middlewares and more.
For example, the useFloating() hook accepts options like placement
, middleware
, whileElementsMounted
to handle advanced use cases.
Incorporating @floating-ui in Your Web Projects
With a solid grasp of the basics, it's easy to start using @floating-ui's components and hooks to implement polished, responsive floating UIs in your own projects.
Some ideas to try:
- Add validation messages in a `` near form fields - Build a dropdown `` for filtering tables - Show user `` cards on hover - Display mobile navigation in a full-screen ``
The library handles collisions, viewport edges, scroll containers and more automatically, allowing you to focus on building a great UX.
The Art of Crafting Custom Tooltips with Floating ui/react tooltip
Floating UI's react tooltip integration provides a robust and flexible solution for adding responsive tooltips to React projects. With full control over styling and behavior, developers can create polished tooltip components tailored to their app's unique needs.
Tooltips serve the vital purpose of communicating extra information upon user interaction. A thoughtfully designed tooltip promotes clarity for the user and contributes to an overall exceptional experience. By using Floating UI under the hood and taking advantage of the powerful react tooltip module, developers gain the capability to build tooltips exceeding static out-of-box implementations.
Achieving Cross-Browser Consistency
Maintaining consistent tooltip presentation across browsers poses challenges, especially when considering factors like preferred placement and preventing overflow or clipping. Thankfully, Floating UI handles these complexities so developers don't have to.
By using the useTooltip
hook provided by floating ui/react tooltip
, tooltips automatically adjust their position based on available space in the viewport. This ensures tooltips remain entirely visible to the user regardless of their screen size or browser.
Additionally, the logic handles fallbacks if the initially calculated placement isn't feasible. For example, if a tooltip set to appear above an element gets cut off at the top of the viewport, Floating UI will attempt to reposition it below the reference element seamlessly.
Such intelligent placement and adjustment sets projects up for cross-browser excellence right from the start when integrating Floating UI's tooltip functionalities.
Highly Customizable for Brand Cohesion
Beyond the out-of-box consistency and smart placement afforded by Floating UI, developers retain full control to customize the tooltips to suit their app's brand and UX needs.
The returned values from useTooltip
include properties to dictate styling such as background color, typography, border radius, padding, and more. By tweaking these values and adding custom CSS, developers can craft tooltips aligned with their overarching design system.
Floating UI handles the tricky logic and calculations while giving the freedom to brand the tooltips however desired. As a result, they seamlessly blend into the surrounding UI rather than looking like an external generic widget.
Responsive Behaviors
Today's web demands fully responsive experiences accommodating any viewport. Floating UI's react tooltip integration promotes responsiveness through automatic repositioning, manual overrides, and control over wrapping behaviors.
As mentioned already, the underlying logic automatically handles repositioning tooltips based on available space. This prevents unwanted clipping on smaller viewports like mobile screens where vertical room runs sparse.
However, developers can also manually override the default placement at any breakpoint by passing a responsive config object. This grants the precision to define exactly where the tooltip should emerge on xs, sm, md, lg, and xl screen sizes.
Finally, the wrap
option gives control over text wrapping within the tooltip container. Set to true
, text will wrap to multiple lines if exceeding the tooltip's width. Disabled, the text remains single line causing overflow. Both behaviors suit certain use cases, so the configurability empowers developers to choose what performs best.
With these various handles to adjust positioning and wrapping, Floating UI's tooltips gracefully handle any responsive requirements thrown their way.
Final Words
Well-designed tooltips require complex logic and calculations under the hood while also allowing extreme customization to match a brand's design aesthetic. With Floating UI's robust and configurable react tooltip integration, developers can handily achieve both facets. Cross-browser consistency comes built-in while styling control gives the freedom to craft tooltips indistinguishable from other UI components. Paired with automatic and manual responsive behaviors, Floating UI's react tooltip module ticks all boxes for delivering exceptional rich tooltips.
Designing with Precision: Floating UI Tooltip Strategies
The Floating UI (@floating-ui) library provides a robust yet customizable tooltip component for building precise and functional user interfaces. As UX designers, we aim to create intuitive experiences that anticipate user needs. Well-designed tooltips play a crucial role in guiding users, providing helpful prompts, and explaining interface elements.
However, generic out-of-the-box tooltips have limitations. With Floating UI's tooltip features, we gain granular control to tailor tooltips to our specific use cases. Whether you need animated hint messages, validation errors, or multi-step onboarding walkthroughs, Floating UI equips us with the flexibility to build highly-tailored tooltip interfaces.
In this guide, we'll explore essential strategies for designing and implementing advanced yet polished tooltips with Floating UI:
Follow Platform Design Guidelines
Adhering to platform-specific design guidelines promotes visual cohesion and familiarity for users. For example, iOS users expect translucent black rectangular prompts with rounded corners. Default Floating UI tooltips match native styling on respective platforms.
Further customize the theme
property to override defaults and match your brand styling. Consistent visuals, regardless of platform, strengthen brand recognition. However, balance consistency with adhering to familiar platform patterns users already understand.
Design for Multiple Interaction Modes
Tooltips primarily exist in two interaction modes:
- Hover - Display upon hovering over an element, disappear on mouse leave. Best for supplementary information.
- Click - Display upon click, disappear on second click. Useful for persistent, multi-step hints.
Floating UI supports both modes through the open
and close
properties. Additionally, the strategy
property handles complex logic like preventing rapid open/close cycles.
Carefully consider which mode best matches the use case. Multi-step tutorials warrant click-based tooltips while optional helper text works well hover-activated.
Animations Enhance User Experience
Animations draw user attention while adding delight and polish. Floating UI’s transition
property allows animating tooltips on open/close with CSS transitions or React spring animations.
Subtle fade or slide animations elegantly catch the user's eye as tooltips display and dismiss. When used sparingly and intentionally, these flourishes enhance UX.
Conversely, excessive, distracting animations potentially harm usability through unnecessary visual clutter. Seek balance and thoughtfully incorporate motion only when it meaningfully improves the interface.
Strategically Position Tooltips
Thoughtful positioning prevents tooltips obstructing important interface elements. Floating UI’s robust placement
property handles this by default, smartly displaying prompts in available screen space.
However, complex interfaces with dynamic content require additional handling. Use the middleware
property to customize positioning logic. With raw access to coordinates and dimensions, we can programmatically handle edge cases like keeping tooltips wholly visible within overflow containers.
With these advanced techniques, Floating UI helps us build clean, usable, and polished tooltip interfaces that elegantly communicate with users. Precision tooltips improve UX when applied judiciously. By providing extensive control over all aspects of tooltips, Floating UI enables us to ship interfaces that feel cohesive across platforms and intuitive during interactions.
Bridging Native Applications with Floating-ui/react native
Floating UI is a fantastic library that enables developers to easily create floating UI elements in their web applications. With smooth animations and smart positioning, it takes the pain out of implementing tooltips, popovers, and other floating components.
Thanks to the power of React Native, Floating UI can now also be used to enhance native mobile applications. The floating-ui/react-native package bridges the gap, making these smooth floating elements available on iOS and Android apps.
Bringing Floating UI Abilities to Mobile
React Native allows developers to build truly native apps for mobile using React and JavaScript. Rather than building separate iOS and Android codebases, React Native translates to native UI components under the hood.
By wrapping the Floating UI web implementation in a React Native compatibility layer, floating-ui/react-native enables the same tooltips, popups and other elements to render beautifully on mobile.
This is fantastic news for developers looking to streamline code across web and mobile, reducing duplication. It also means mobile apps can benefit from the carefully designed animation curves and smart positioning logic that the Floating UI library is loved for.
Usage with React Native Components
Importing and using Floating UI with React Native components is easy. Here is a simple example to display a tooltip on press of a ``:
import { Button } from 'react-native';
import { useFloating } from 'floating-ui/react-native';
function MyComponent() {
const { x, y, strategy, refs } = useFloating({
placement: 'top',
middleware: [offset(10)],
});
return (
<Button
onPress={() => refs.setReference(buttonRef.current)}
>
Press me
<Tooltip x={x} y={y} strategy={strategy}>
I'm a tooltip!
</Tooltip>
</Button>
);
}
The API mirrors usage on the web, with the refs and positioning coordinated by Floating UI. Components simply need passing appropriate placement props.
A Uniform Development Experience
Using the same Floating UI library across web, Android and iOS results in a uniform interface. Tooltips, popups and notifications can slide neatly between platforms with shared logic.
For developers active across web and app projects, this continuity accelerates development. Rather than learning platform-specific implementations, knowledge transfers between projects.
For end users, visual elements behaving consistently also promotes intuitive understanding. This allows apps to focus user testing on more meaningful points of distinction.
Conclusion
The introduction of floating-ui/react-native empowers React Native developers to build great mobile UIs. Parity with the web Floating UI library means fast, animated, elegantly positioned floating elements on native platforms. For developers and users alike, this crossover stands to enrich application experiences all round.
Wrapping Up: The Power and Versatility of @floating-ui
@floating-ui is a versatile JavaScript library that enables developers to position elements relative to other elements on a page. Some key strengths that make it a robust tool for building floating UI components:
- Framework Agnostic: @floating-ui works across React, Vue, Angular, and other popular frameworks. It also works with vanilla JavaScript. This flexibility allows it to be integrated into virtually any web project.
- Multi-Platform Support: In addition to web browsers, @floating-ui supports React Native to build floating UIs for mobile apps. There are also bindings available for Svelte and other frameworks.
- Granular Control: The library provides granular methods like
offset
,shift
,resize
, andupdate
to control floating element positioning and behavior. Developers have a high degree of control. - Focus Management: @floating-ui handles complexity around managing focus events when floating elements are displayed/hidden. This removes a common pain point.
- Automated Positioning: Elements can be automatically positioned relative to references like viewports, parents, or other elements on the page. This saves manual effort.
In summary, @floating-ui is shaping up to be a versatile tool for crafting all kinds of floating UI components from tooltips to dropdowns across platforms. With its framework-agnostic approach, fine-grained control methods, and automated positioning - it promises to boost developer productivity and UI capabilities.