Skip to content

6 min readLoading views

Floating UI - Coordinate System

A deep dive into how Floating UI calculates tooltip and popup positions.

Introduction

Ever wondered how libraries like Floating UI know exactly where to place a tooltip? It all comes down to understanding the browser's coordinate system and some clever math. In this article, we'll break down the positioning logic step by step, from basic rectangles to the complete computeCoordsFromPlacement function.

Floating UI uses the browser's coordinate system, where the origin (0, 0) is at the top-left corner of the viewport. Let's start by understanding how a single rectangle is defined:

interface Rect {  x: number;  y: number;  width: number;  height: number;}
  • x/y – X/Y-coordinates of the rectangle origin relative to window,
  • width/height – width/height of the rectangle (can be negative).

As long as we know the XY coordinates and the element's height and width, we can derive the properties below.

  • top/bottom – Y-coordinate for the top/bottom rectangle edge,
  • left/right – X-coordinate for the left/right rectangle edge.

The diagram above illustrates these relationships visually. With this foundation, the following calculations should be straightforward:

left = xtop = yright = x + widthbottom = y + heightcenterX = x + width / 2centerY = y + height / 2`

The Two Elements

There are two elements in the floating UI world: reference, which is the anchor element (button, link, etc.), and floating, which is the positioned element (tooltip, dropdown, etc.).

Once we know how to identify the positions of the two elements, we can start calculating the relationship between them.

Placement Types

Sides

There are 4 possible sides where the floating element can be positioned:

type Side = 'top' | 'right' | 'bottom' | 'left';

Alignments

There are 2 alignment options that determine how the floating element aligns along the reference edge:

type Alignment = 'start' | 'end';

Combined Placements

When you combine a side with an alignment (or leave it centered by default), you get the 12 possible placements:

type Placement =  | 'top'  | 'top-start'  | 'top-end'  | 'right'  | 'right-start'  | 'right-end'  | 'bottom'  | 'bottom-start'  | 'bottom-end'  | 'left'  | 'left-start'  | 'left-end';

Axes Explained

The Side Axis (The "Attachment" Axis)

This axis is perpendicular to the edge of the reference element. It determines how far away the floating element is from the anchor.

  • For top / bottom: The Side Axis is y. You change the y coordinate to move the tooltip further up or down from the button.
  • For left / right: The Side Axis is x. You change the x coordinate to move the tooltip further left or right.

The Alignment Axis (The "Sliding" Axis)

This axis is parallel to the edge of the reference element. It determines where the element "slides" along that edge to satisfy start, center, or end.

  • For top / bottom: The Alignment Axis is x. The tooltip slides left or right to align its corner or center with the button.
  • For left / right: The Alignment Axis is y. The tooltip slides up or down to align with the button's height.
function getSide(placement: Placement): Side {  return placement.split('-')[0];}function getSideAxis(placement: Placement): Axis {  const side = getSide(placement); // 'top' | 'right' | 'bottom' | 'left'  return (side === 'top' || side === 'bottom') ? 'y' : 'x';}function getAlignmentAxis(placement: Placement): Axis {  return getOppositeAxis(getSideAxis(placement));}function getOppositeAxis(axis: Axis): Axis {  return axis === 'x' ? 'y' : 'x';}function getAxisLength(axis: Axis): 'width' | 'height' {  return axis === 'x' ? 'width' : 'height';}

The Math - computeCoordsFromPlacement

When you say placement: 'bottom', you're telling Floating UI: "Put the floating element below the reference." But what does "below" actually mean in terms of x and y coordinates? This is what computeCoordsFromPlacement figures out. Let's break it down step by step.

For any placement, we need to answer:

  • Where does the floating element's LEFT edge go? (the x coordinate)
  • Where does the floating element's TOP edge go? (the y coordinate)

Note

Remember: x and y always refer to the top-left corner of the floating element.

Calculate Center Points

Before we position by side, we calculate where the floating element would be if it were perfectly centered on the reference:

// Center horizontally relative to referenceconst commonX = reference.x + reference.width / 2 - floating.width / 2;// Center vertically relative to referenceconst commonY = reference.y + reference.height / 2 - floating.height / 2;

So what does this formula actually mean?

Step 1: Start at the Left Edge

As mentioned above, every positioned element in the browser has an x property that represents its left edge. When we write ref.x, we're starting at the button's left edge. Think of this as our starting line. We know where the button begins, and that's our anchor point.

Step 2: Move to the Center Line

Now we need to find the center of the button. To do this, we add half of the button's width: + (ref.width / 2). If a button starts at 300px and is 200px wide, its center is at 400px (300 + 100). This gives us the vertical center line where both elements should align.

Step 3: Back Up by Half the Tooltip Width

Here's the crucial step that trips people up. If we placed our tooltip starting at the center line, it would be off-center—the tooltip's left edge would be at the center, pushing the whole tooltip too far right.

We need to back up by half the tooltip's width: - (float.width / 2). This "backs up" the tooltip so that its center (not its left edge) sits on the center line.

The formula essentially says: "Find the reference center, then offset backwards by half the floating element's width." This ensures both centers align perfectly.

Position by Side

Once we know the starting point for the floating element in x, we place the element above the reference and center it horizontally.

case 'top':  coords = {    x: commonX,                        // Use centered x    y: reference.y - floating.height   // Position above  };

The y calculation explained:

We want floating's BOTTOM edge to touch reference's TOP edge. But we set the TOP edge (y coordinate), not the bottom. So: floating.y = reference.y - floating.height

        ┌─────────────────┐ ◄── floating.y = ref.y - float.height        │                 │              = 100 - 60 = 40        │    FLOATING     │        │   (height: 60)  │        └─────────────────┘ ◄── floating bottom = 40 + 60 = 100        ┌─────────────────┐ ◄── reference.y = 100        │    REFERENCE    │        └─────────────────┘

The floating element's bottom (100) meets reference's top (100)

Calculate Alignment Offset

This step we will need to know how far to shift for start/end alignment

const alignLength = getAxisLength(alignmentAxis); // If it's top/bottom placements, it returns "width" otherwise returns "height"const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;

What is commonAlign?

For horizontal alignment (top/bottom placements):

reference.width / 2 - floating.width / 2;
  • If the reference wider than floating, the common align will be positive value.
  • If the floating wider than reference, the common align will be negative value.

Apply Alignment

const alignment = getAlignment(placement); // 'start' | 'end' | undefinedconst alignmentAxis = getAlignmentAxis(placement);const isVertical = sideAxis === 'y'; // true for top/bottomswitch (alignment) {  case 'start':    coords[alignmentAxis] -= commonAlign;    break;  case 'end':    coords[alignmentAxis] += commonAlign;    break;  // default (center): no adjustment needed}
  • 'start' alignment: Align floating's start edge with reference's start edge
  • 'end' alignment: Align floating's end edge with reference's end edge

If the placement is top, for start alignment, subtract commonAlign from x, coords.x -= commonAlign, and for end, add commonAlign from x, coords.x -= commonAlign.

Final Formula Table

Here's the complete reference for all placement calculations:

Placementxy
topref.x + ref.w/2 - float.w/2ref.y - float.h
top-startref.xref.y - float.h
top-endref.x + ref.w - float.wref.y - float.h
bottomref.x + ref.w/2 - float.w/2ref.y + ref.h
bottom-startref.xref.y + ref.h
bottom-endref.x + ref.w - float.wref.y + ref.h
leftref.x - float.wref.y + ref.h/2 - float.h/2
left-startref.x - float.wref.y
left-endref.x - float.wref.y + ref.h - float.h
rightref.x + ref.wref.y + ref.h/2 - float.h/2
right-startref.x + ref.wref.y
right-endref.x + ref.wref.y + ref.h - float.h

Conclusion

Understanding Floating UI's coordinate system is fundamental to mastering tooltip and popup positioning. Let's recap the key concepts:

  1. The Coordinate System: Browser coordinates start at the top-left corner (0, 0), with X increasing rightward and Y increasing downward.

  2. Two Elements: Every floating interaction involves a reference element (the anchor) and a floating element (the positioned content).

  3. Placements: There are 12 placements combining 4 sides (top, right, bottom, left) with alignments (start, end, or centered by default).

  4. Two Axes:

    • The Side Axis determines the distance between elements
    • The Alignment Axis determines where the floating element slides along the reference edge
  5. The Centering Formula: ref.x + ref.width/2 - float.width/2 ensures perfect center alignment by finding the reference center and then backing up by half the floating element's size.

With this foundation, you're now equipped to debug positioning issues, customize Floating UI's behavior, or even build your own positioning logic. The next time a tooltip appears in the wrong place, you'll know exactly which axis and calculation to investigate!

Playground

Now that you understand the math behind Floating UI's positioning system, it's time to put that knowledge into practice! Use the interactive playground below to experiment with different placements and dimensions. Try adjusting the reference and floating element sizes to see how the coordinates change in real-time. Pay attention to how the Side Axis and Align Axis indicators update as you switch between placements, this will help solidify your understanding of how the two axes work together.

View only
import React, { useState, useMemo } from 'react';const refX = 320;const refY = 280;const colors = {  bgPage: '#f9fafb',  sidebar: '#ffffff',  border: '#e5e7eb',  textMain: '#111827',  textMuted: '#6b7280',  axis: '#374151',  input: '#ef4444',  derived: '#172c66',  guide: '#e5e7eb',  side: '#10b981',  align: '#f59e0b',  refFill: 'rgba(99, 102, 241, 0.05)',  refStroke: '#001858',  floatFill: 'rgba(139, 92, 246, 0.05)',  floatStroke: '#33272a',};const styles = {  app: {    display: 'flex',    height: '100vh',    backgroundColor: colors.bgPage,    color: colors.textMain,    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',  },  sidebar: {    width: '300px',    backgroundColor: colors.sidebar,    borderRight: `1px solid ${colors.border}`,    display: 'flex',    flexDirection: 'column',    flexShrink: 0,    height: '100%',    padding: '0 0 0 10px',  },  sidebarHeader: {    padding: '16px',    borderBottom: `1px solid ${colors.border}`,    fontSize: '12px',    fontWeight: '600',    textTransform: 'uppercase',    letterSpacing: '0.05em',    color: colors.textMuted,  },  sidebarSection: {    padding: '16px',    borderBottom: `1px solid ${colors.border}`,    marginBottom: '18px',  },  propertyRow: {    display: 'flex',    alignItems: 'center',    justifyContent: 'space-between',    marginBottom: '12px',    fontSize: '11px',  },  propertyLabel: {    color: colors.textMuted,    width: '80px',  },  propertyInputGroup: {    display: 'flex',    alignItems: 'center',    gap: '8px',    flex: 1,  },  propertyValue: {    width: '35px',    textAlign: 'right',    fontWeight: '500',    color: colors.textMain,  },  canvas: {    flex: 1,    position: 'relative',    padding: '40px',    display: 'flex',    alignItems: 'center',    justifyContent: 'center',  },  placementGrid: {    display: 'grid',    gridTemplateColumns: 'repeat(3, 1fr)',    gap: '4px',    backgroundColor: colors.bgApp,    padding: '4px',    borderRadius: '6px',  },  placementBtn: (active) => ({    padding: '6px 2px',    fontSize: '10px',    border: 'none',    borderRadius: '4px',    backgroundColor: active ? '#FFFFFF' : 'transparent',    boxShadow: active ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',    color: active ? colors.textMain : colors.textMuted,    cursor: 'pointer',    fontWeight: active ? '600' : '400',  }),  badge: (bgColor) => ({    backgroundColor: bgColor,    color: 'white',    padding: '2px 6px',    borderRadius: '4px',    fontSize: '9px',    fontWeight: 'bold',    marginLeft: '6px',  }),};const App = () => {  // State for parameters  const [placement, setPlacement] = useState('top');  const [refWidth, setRefWidth] = useState(200);  const [refHeight, setRefHeight] = useState(80);  const [floatWidth, setFloatWidth] = useState(160);  const [floatHeight, setFloatHeight] = useState(60);  const [offset, setOffset] = useState(0);  // Computation Logic  const floatPos = useMemo(() => {    const [side, align] = placement.split('-');    let x, y;    if (side === 'top') y = refY - floatHeight - offset;    else if (side === 'bottom') y = refY + refHeight + offset;    else if (side === 'left') x = refX - floatWidth - offset;    else if (side === 'right') x = refX + refWidth + offset;    if (side === 'top' || side === 'bottom') {      if (!align) x = refX + refWidth / 2 - floatWidth / 2;      else if (align === 'start') x = refX;      else if (align === 'end') x = refX + refWidth - floatWidth;    } else {      if (!align) y = refY + refHeight / 2 - floatHeight / 2;      else if (align === 'start') y = refY;      else if (align === 'end') y = refY + refHeight - floatHeight;    }    return { x: Math.round(x), y: Math.round(y) };  }, [placement, refWidth, refHeight, floatWidth, floatHeight, offset]);  const axisInfo = useMemo(() => {    const [side, align] = placement.split('-');    const isVertical = side === 'top' || side === 'bottom';    return {      side,      align: align || 'center',      isVertical,      sideAxis: isVertical ? 'Y' : 'X',      alignAxis: isVertical ? 'X' : 'Y',    };  }, [placement]);  // Overlap Fix Logic  const labels = useMemo(() => {    const xDist = Math.abs(floatPos.x - refX);    const yDist = Math.abs(floatPos.y - refY);    // Check if float point is very close to ref point to flip label orientation    const flipY = yDist < 40 && floatPos.y < refY;    const flipX = xDist < 60;    return {      floatY: flipY ? 20 : -10,      floatX: flipX ? -15 : 15,      floatXAnchor: flipX ? 'end' : 'start',    };  }, [floatPos, refX, refY]);  return (    <div style={styles.app}>      {/* Figma Sidebar */}      <aside style={styles.sidebar}>        <div style={styles.sidebarHeader}>Properties</div>        <div style={styles.sidebarSection}>          <div style={{ ...styles.propertyRow, marginBottom: '8px' }}>            <span style={{ fontWeight: '600', color: colors.textMain }}>Placement</span>          </div>          <div style={styles.placementGrid}>            {[              'top-start',              'top',              'top-end',              'left-start',              'left',              'left-end',              'right-start',              'right',              'right-end',              'bottom-start',              'bottom',              'bottom-end',            ].map((p) => (              <button key={p} style={styles.placementBtn(placement === p)} onClick={() => setPlacement(p)}>                {p.replace('-', '\n')}              </button>            ))}          </div>        </div>        <div style={styles.sidebarSection}>          <div style={{ ...styles.propertyRow, marginBottom: '16px' }}>            <span style={{ fontWeight: '600', color: colors.textMain }}>Dimensions</span>          </div>          {[            { label: 'Ref W', val: refWidth, set: setRefWidth, min: 80, max: 300 },            { label: 'Ref H', val: refHeight, set: setRefHeight, min: 40, max: 150 },            { label: 'Float W', val: floatWidth, set: setFloatWidth, min: 80, max: 300 },            { label: 'Float H', val: floatHeight, set: setFloatHeight, min: 40, max: 120 },            // { label: 'Offset', val: offset, set: setOffset, min: 0, max: 80 },          ].map((item) => (            <div key={item.label} style={styles.propertyRow}>              <span style={styles.propertyLabel}>{item.label}</span>              <div style={styles.propertyInputGroup}>                <input                  type="range"                  min={item.min}                  max={item.max}                  value={item.val}                  onChange={(e) => item.set(parseInt(e.target.value))}                  style={{ flex: 1, cursor: 'pointer' }}                />                <span style={styles.propertyValue}>{item.val}</span>              </div>            </div>          ))}        </div>        <div style={styles.sidebarSection}>          <div style={{ ...styles.propertyRow, marginBottom: '12px' }}>            <span style={{ fontWeight: '600', color: colors.textMain }}>Axis Info</span>          </div>          <div style={styles.propertyRow}>            <span>Side Axis</span>            <span style={{ ...styles.badge(colors.side) }}>Axis {axisInfo.sideAxis}</span>          </div>          <div style={styles.propertyRow}>            <span>Align Axis</span>            <span style={{ ...styles.badge(colors.align) }}>Axis {axisInfo.alignAxis}</span>          </div>          <div style={{ marginTop: '12px', fontSize: '10px', color: colors.textMuted, lineHeight: '1.4' }}>            The <b>Side Axis</b> ({axisInfo.sideAxis}) handles the {axisInfo.isVertical ? 'vertical' : 'horizontal'}{' '}            gap. The <b>Align Axis</b> ({axisInfo.alignAxis}) handles the{' '}            {axisInfo.isVertical ? 'horizontal' : 'vertical'} alignment.          </div>        </div>      </aside>      {/* Main Canvas Area */}      <main style={styles.canvas}>        <svg viewBox="0 0 800 600" style={{ width: '100%', height: '100%', overflow: 'visible' }}>          {/* Main Coordinate Axes */}          <g opacity="0.3">            <path d="M40 40 L760 40" stroke={colors.textMain} strokeWidth="1.5" fill="none" />            <path d="M40 40 L40 560" stroke={colors.textMain} strokeWidth="1.5" fill="none" />            <text x="770" y="45" fontSize="12" fontWeight="bold">              X            </text>            <text x="35" y="580" fontSize="12" fontWeight="bold">              Y            </text>          </g>          {/* Reference Block */}          <g>            <rect              x={refX}              y={refY}              width={refWidth}              height={refHeight}              rx="4"              fill={colors.refFill}              stroke={colors.refStroke}              strokeWidth="2"            />            <text              x={refX + refWidth / 2}              y={refY + refHeight / 2 + 5}              textAnchor="middle"              fontSize="12"              fontWeight="700"              fill={colors.refStroke}            >              Reference            </text>            {/* Ref Markers */}            <path d={`M40 ${refY} L${refX} ${refY}`} stroke={colors.input} strokeWidth="1" strokeDasharray="4 2" />            <text x={refX / 2} y={refY - 6} textAnchor="middle" fill={colors.input} fontSize="11" fontWeight="600">              ref.y = {refY}            </text>            <path d={`M${refX} 40 L${refX} ${refY}`} stroke={colors.input} strokeWidth="1" strokeDasharray="4 2" />            <text x={refX + 8} y={refY / 2 + 20} fill={colors.input} fontSize="11" fontWeight="600">              ref.x = {refX}            </text>            <circle cx={refX} cy={refY} r="3" fill={colors.input} />          </g>          {/* Floating Block */}          <g>            <rect              x={floatPos.x}              y={floatPos.y}              width={floatWidth}              height={floatHeight}              rx="4"              fill={colors.floatFill}              stroke={colors.floatStroke}              strokeWidth="2"            />            <text              x={floatPos.x + floatWidth / 2}              y={floatPos.y + floatHeight / 2 + 5}              textAnchor="middle"              fontSize="12"              fontWeight="700"              fill={colors.floatStroke}            >              Floating            </text>            {/* Float Markers with Anti-Collision */}            <path              d={`M40 ${floatPos.y} L${floatPos.x} ${floatPos.y}`}              stroke={colors.derived}              strokeWidth="1"              strokeDasharray="4 2"            />            <text              x={floatPos.x / 2}              y={floatPos.y + labels.floatY}              textAnchor="middle"              fill={colors.derived}              fontSize="11"              fontWeight="800"            >              float.y = {floatPos.y}            </text>            <path              d={`M${floatPos.x} 40 L${floatPos.x} ${floatPos.y}`}              stroke={colors.derived}              strokeWidth="1"              strokeDasharray="4 2"            />            <text              x={floatPos.x + labels.floatX}              y={floatPos.y / 2 + 20}              textAnchor={labels.floatXAnchor}              fill={colors.derived}              fontSize="11"              fontWeight="800"            >              float.x = {floatPos.x}            </text>            <circle cx={floatPos.x} cy={floatPos.y} r="3" fill={colors.derived} />          </g>          {/* DYNAMIC AXIS LABELS: Side Axis and Align Axis */}          <g>            {axisInfo.isVertical ? (              <>                {/* Vertical Side Axis Label (Y) - shows the gap between ref and float */}                <line                  x1={refX + refWidth / 2}                  y1={axisInfo.side === 'top' ? refY : refY + refHeight}                  x2={refX + refWidth / 2}                  y2={axisInfo.side === 'top' ? floatPos.y + floatHeight : floatPos.y}                  stroke={colors.side}                  strokeWidth="3"                />                {(() => {                  const lineY1 = axisInfo.side === 'top' ? refY : refY + refHeight;                  const lineY2 = axisInfo.side === 'top' ? floatPos.y + floatHeight : floatPos.y;                  const midY = (lineY1 + lineY2) / 2;                  return (                    <>                      <rect                        x={refX + refWidth / 2 + 10}                        y={midY - 10}                        width="60"                        height="20"                        fill="white"                        stroke={colors.side}                        rx="4"                      />                      <text                        x={refX + refWidth / 2 + 40}                        y={midY + 4}                        textAnchor="middle"                        fill={colors.side}                        fontSize="10"                        fontWeight="800"                      >                        SIDE (Y)                      </text>                    </>                  );                })()}                {/* Horizontal Align Axis Indicator (X) */}                <g>                  <line                    x1={floatPos.x}                    y1={floatPos.y + floatHeight / 2}                    x2={floatPos.x + floatWidth}                    y2={floatPos.y + floatHeight / 2}                    stroke={colors.align}                    strokeWidth="2"                    strokeDasharray="4"                  />                  <rect                    x={floatPos.x + floatWidth / 2 - 30}                    y={floatPos.y + (axisInfo.side === 'top' ? -25 : floatHeight + 7)}                    width="60"                    height="18"                    fill="white"                    stroke={colors.align}                    rx="4"                  />                  <text                    x={floatPos.x + floatWidth / 2}                    y={floatPos.y + (axisInfo.side === 'top' ? -12 : floatHeight + 20)}                    textAnchor="middle"                    fill={colors.align}                    fontSize="10"                    fontWeight="800"                  >                    ALIGN (X)                  </text>                </g>              </>            ) : (              <>                {/* Horizontal Side Axis Label (X) - shows the gap between ref and float */}                <line                  x1={axisInfo.side === 'left' ? refX : refX + refWidth}                  y1={refY + refHeight / 2}                  x2={axisInfo.side === 'left' ? floatPos.x + floatWidth : floatPos.x}                  y2={refY + refHeight / 2}                  stroke={colors.side}                  strokeWidth="3"                />                {(() => {                  const lineX1 = axisInfo.side === 'left' ? refX : refX + refWidth;                  const lineX2 = axisInfo.side === 'left' ? floatPos.x + floatWidth : floatPos.x;                  const midX = (lineX1 + lineX2) / 2;                  return (                    <>                      <rect                        x={midX - 30}                        y={refY + refHeight / 2 - 30}                        width="60"                        height="20"                        fill="white"                        stroke={colors.side}                        rx="4"                      />                      <text                        x={midX}                        y={refY + refHeight / 2 - 16}                        textAnchor="middle"                        fill={colors.side}                        fontSize="10"                        fontWeight="800"                      >                        SIDE (X)                      </text>                    </>                  );                })()}                {/* Vertical Align Axis Indicator (Y) */}                <g>                  <line                    x1={floatPos.x + floatWidth / 2}                    y1={floatPos.y}                    x2={floatPos.x + floatWidth / 2}                    y2={floatPos.y + floatHeight}                    stroke={colors.align}                    strokeWidth="2"                    strokeDasharray="4"                  />                  <rect                    x={floatPos.x + (axisInfo.side === 'left' ? floatWidth + 7 : -67)}                    y={floatPos.y + floatHeight / 2 - 9}                    width="60"                    height="18"                    fill="white"                    stroke={colors.align}                    rx="4"                  />                  <text                    x={floatPos.x + (axisInfo.side === 'left' ? floatWidth + 37 : -37)}                    y={floatPos.y + floatHeight / 2 + 4}                    textAnchor="middle"                    fill={colors.align}                    fontSize="10"                    fontWeight="800"                  >                    ALIGN (Y)                  </text>                </g>              </>            )}          </g>        </svg>      </main>      <style>{`        body {          min-height: 100vh;        }        input[type="range"] {          -webkit-appearance: none;          height: 2px;          background: #E6E6E6;          border-radius: 2px;          outline: none;        }        input[type="range"]::-webkit-slider-thumb {          -webkit-appearance: none;          width: 12px;          height: 12px;          background: #FFFFFF;          border: 1px solid #B3B3B3;          border-radius: 50%;          cursor: pointer;          box-shadow: 0 1px 2px rgba(0,0,0,0.1);        }        input[type="range"]:hover::-webkit-slider-thumb {          border-color: #18A0FB;        }      `}</style>    </div>  );};export default App;
Output
Press Run to see the output here.The first run downloads the React engine, about 200 kB.
Loading likes