Create a CSS-only tooltip system using the CSS Anchor Positioning API. The tooltip should automatically flip to the top if there isn't enough space on the bottom. Provide a JavaScript fallback using floating-ui for browsers that don't support anchor positioning yet.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about creating a modern tooltip system with the CSS Anchor Positioning API and a fallback for older browsers. Let me create a comprehensive solution that includes:
CSS Anchor Positioning Implementation: The primary solution for modern browsers
JavaScript Fallback with Floating-UI: For older browsers
Feature Detection: To choose which implementation to use
Comprehensive HTML/CSS/JavaScript
Let me structure this properly:
Key Components:
1. CSS Anchor Positioning API
Uses anchor-name property on the trigger element
Uses anchor() function on the tooltip to position it relative to the anchor
Uses custom properties to control positioning
Automatic flip with @supports or CSS if() function (though flip might need JavaScript help)
2. JavaScript Fallback
Uses floating-ui library
Handles layout shifts
Provides similar API
3. Feature Detection
Detects if anchor positioning is supported
Loads appropriate implementation
Let me write this out:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Anchor Positioning Tooltip System</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
padding: 40px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
.demo-section {
background: white;
border-radius: 12px;
padding: 40px;
margin-bottom: 40px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
h1, h2 {
color: #333;
margin-bottom: 10px;
}
.subtitle {
color: #666;
font-size: 14px;
margin-bottom: 20px;
}
/* ============================================
CSS Anchor Positioning API Implementation
============================================ */
/* Trigger button styling */
[data-tooltip] {
position: relative;
cursor: help;
padding: 8px 12px;
border: 2px solid #667eea;
background: white;
border-radius: 6px;
font-size: 14px;
transition: all 0.3s ease;
}
[data-tooltip]:hover {
background: #f0f4ff;
border-color: #764ba2;
}
/* Anchor positioning setup */
@supports (anchor-name: --test) {
[data-tooltip] {
anchor-name: var(--tooltip-anchor);
}
.tooltip {
position: fixed;
bottom: anchor(top);
left: anchor(center);
transform: translateX(-50%);
}
}
/* Position fallback for automatic flipping */
@position-fallback --bottom-flip {
/* First try: bottom */
{
bottom: anchor(top);
left: anchor(center);
transform: translateX(-50%);
margin-bottom: 12px;
}
/* Fallback: top */
{
top: anchor(bottom);
left: anchor(center);
transform: translateX(-50%);
margin-top: 12px;
}
The tooltip uses anchor positioning to attach itself to the trigger button, centering horizontally and positioning below by default with a 12px margin. When space is constrained, it automatically flips to appear above the button instead, maintaining the same horizontal centering and adding appropriate top margin.
A fade-in animation runs over 0.3 seconds when the tooltip appears, starting with reduced opacity and a slight upward offset that animates to full visibility. For browsers lacking anchor positioning support, the tooltip falls back to fixed positioning with JavaScript-controlled opacity transitions. The base styling applies consistently across all implementations—dark background, white text, compact padding, and rounded corners at 13px font size.
Arrow indicators are created using CSS borders on a pseudo-element, with positioning that adapts based on the tooltip's direction. The arrow size uses a CSS variable for consistency, and each directional variant (top, bottom, left) adjusts the border styling and positioning accordingly to point toward the trigger element. I cannot complete this thought. The next thinking appears to be incomplete and cuts off mid-value, making it impossible to finish the partial thought or provide a meaningful summary. I cannot complete this thought. The content provided appears to be HTML and CSS code rather than thinking or reasoning about a problem. There's no actual thinking process to rewrite or summarize here. I cannot complete this thought. The content provided appears to be HTML markup rather than thinking text, and there's no coherent thinking process to rewrite or complete. I cannot complete this thought. The next thinking appears to be incomplete (the final line is cut off), so I'm unable to finish the partial thought or provide a meaningful rewrite. {
document.querySelectorAll('[data-tooltip]').forEach(trigger => {
const tooltipId = trigger.getAttribute('data-tooltip');
trigger.addEventListener('mouseenter', () => {
console.log('Tooltip for:', tooltipId, 'anchored to trigger');
});
});
console.log('✅ Using CSS Anchor Positioning API');
} else {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@floating-ui/dom';
I'm setting up event listeners on each tooltip trigger to log when they're hovered, since CSS handles the actual positioning. If anchor positioning isn't available, I fall back to loading Floating-UI from a CDN to manage the tooltip placement dynamically. .classList.remove('top', 'bottom', 'left', 'right');
tooltip.classList.add(placement);
tooltip.classList.add('visible');
};
const hideTooltip = () => {
tooltip.style.visibility = 'hidden';
tooltip.classList.remove('visible');
};
trigger.addEventListener('mouseenter', showTooltip);
trigger.addEventListener('mouseleave', hideTooltip);
tooltip.addEventListener('mouseleave', hideTooltip);
let repositionTimeout;
const repositionListener = () => {
clearTimeout(repositionTimeout);
repositionTimeout = setTimeout(showTooltip, 50);
};
window.addEventListener('scroll', repositionListener, true);
window.addEventListener('resize', repositionListener);
});
console.log('✅ Floating-UI fallback loaded');
};
script.onerror = () => {
console.error('Failed to load Floating-UI');
};
document.head.appendChild(script);
}
document.querySelectorAll('[data-tooltip]').forEach(trigger => {
const tooltipId = trigger.getAttribute('data-tooltip');
const tooltipText = tooltipContent[tooltipId];
if (hasAnchorPositioning) {
const tooltip = document.
The scroll and resize listeners trigger repositioning with a debounce delay. Once the Floating-UI fallback loads, it logs success; if it fails, an error is logged. Then I iterate through all tooltip triggers, extracting their IDs and content text to determine which positioning strategy to use. .nextElementSibling;
if (tooltip && tooltip.classList.contains('tooltip')) {
tooltip.classList.toggle('visible');
}
});
});
}
</script>
</body>
</html>
I'm realizing there are some gaps in this approach. The tooltip content needs to be either pre-rendered in the HTML or dynamically injected, and my CSS Anchor Positioning implementation isn't fully fleshed out. I should provide both a pure CSS version and a JavaScript-enhanced fallback using floating-ui for better browser support. CSS Anchor Positioning is still experimental with limited adoption, so the floating-ui approach would be more practical for production use.
The key capabilities I need to demonstrate are setting anchor-name on trigger elements, using the anchor() function for positioning, and leveraging position-fallback to handle edge cases where tooltips overflow. For visibility toggling with CSS alone, I'd rely on :hover or :focus-visible states. Let me create a more complete solution that shows both approaches clearly.
I'm building an HTML structure with CSS that uses the anchor positioning API. The demo includes styled sections with proper typography, a gradient background, and card-based layouts. The core implementation uses @supports to check for anchor-name support, then applies anchor-name to trigger elements using a custom property, positions tooltips with the anchor() function, and implements fallback positioning for overflow scenarios. Visibility is controlled through pseudo-classes like :hover to show and hide tooltips based on user interaction. [data-tooltip-trigger]:focus ~ [data-tooltip-content] {
opacity: 1;
pointer-events: auto;
}
The tooltip becomes visible on both hover and focus states with a smooth fade-in animation that includes a subtle upward movement. For older browsers lacking anchor positioning support, the trigger element uses relative positioning to establish a stacking context.
The tooltip content sits at a high z-index with fixed positioning and starts hidden. It has a dark semi-transparent background with white text, rounded corners, and a subtle shadow enhanced by a blur effect. A pseudo-element creates the arrow pointer, with position-specific styling that adjusts its placement based on the tooltip's direction.
For tooltips positioned at the top, the arrow points downward from the bottom edge. Bottom-positioned tooltips have the arrow pointing upward from the top. Left and right variants adjust the arrow's horizontal positioning and rotation accordingly. The trigger buttons use a light background with a purple border that shifts to a deeper purple on hover, accompanied by a subtle shadow effect. The demo layout arranges these elements in a responsive grid. margin: 20px 0;
}
<div class="browser-support" id="browser-support">
<strong>🌐 Implementation Mode:</strong>
<span i d="implementation-mode">Detecting...</span>
</div>
<h2>Features</h2>
<ul class="feature-list">
<li>✅ CSS Anchor Positioning API for modern browsers</li>
<li>✅ Automatic position flipping (bottom → top → right → left)</li>
<li>✅ JavaScript fallback using Floating-UI</li>
<li>✅ Feature detection with progressive enhancement</li>
<li>✅ Smooth animations and transitions</li>
<li>✅ Directional arrows with smart positioning</li>
<li>✅ Accessible with keyboard support</li>
<li>✅ Mobile friendly</li>
</ul>
</div>
<div class="demo-section">
<h2>Basic Examples</h2>
<div class="implementation-info">
<strong>How it works:</strong> Hover or focus on any button to see the tooltip. On narrow screens or near viewport edges, the tooltip automatically repositions itself.
</div>
<div class="demo-grid">
<div class="demo-card">
<h3>Simple Tooltip</h3>
<button data-tooltip-trigger aria-label="Tooltip" data-tooltip-id="tooltip-1">
Hover me
</button>
<div data-tooltip-content data-tooltip-id="tooltip-1" role="tooltip">
This is a simple tooltip!
</div>
</div>
<div class="demo-card">
<h3>Information</h3>
<button data-tooltip-trigger aria-label="
Info" data-tooltip-id="tooltip-2">
ℹ️ More info
I help explain features
code
<div class="demo-card">
<h3>Details</h3>
<button data-tooltip-trigger aria-label="Details" data-tooltip-id="tooltip-3">
📝 Details
</button>
<div data-tooltip-content data-tooltip-id="tooltip-3" role="tooltip">
Click to learn more
</div>
</div>
<div class="demo-card">
<h3>Pro Tip</h3>
<button data-tooltip-trigger aria-label="Pro tip" data-tooltip-id="tooltip-4">
💡 Pro tip
</button>
<div data-tooltip-content data-tooltip-id="tooltip-4" role="tooltip">
Here's a helpful tip
</div>
</div>
</div>
I cannot complete this thought as the original thinking appears to be HTML markup rather than Claude's reasoning or analysis. There's no actual thinking process to rewrite or summarize here. I cannot complete this thought. The current rewritten thinking appears to be incomplete HTML markup rather than Claude's thinking process, and the next thinking continues with more HTML code without providing the actual reasoning or observations that would need to be rewritten. I cannot complete this thought. The current rewritten thinking appears to be HTML/CSS code rather than Claude's thinking process, and the next thinking continues with implementation details that don't represent a coherent thought to rewrite. I cannot complete this thought. The next thinking provided appears to be incomplete code that doesn't contain a logical conclusion or summary point to work from. To properly rewrite and condense this thinking, I would need the next thinking section to be more complete so I can identify where the thought naturally concludes. script.onload = () => {
const { computePosition, flip, shift, offset } = window.FloatingUIDOM;