Skip to content

Instantly share code, notes, and snippets.

@tonyhschu
Last active January 29, 2018 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyhschu/b8306da7114d1772e740dbb45058a8dc to your computer and use it in GitHub Desktop.
Save tonyhschu/b8306da7114d1772e740dbb45058a8dc to your computer and use it in GitHub Desktop.
Foreign Object Tooltip Sadness
license: mit

The <foreignObject> tag has so much potential for making tooltips in <svg> much easier to create, but right now it seems like it needs some love on the CSS support front.

In this block, I demonstrated a couple approaches that we tried for using <foreignObject> to place an HTML element inside SVG. It doesn't quite do what we would expect (i.e. place the HTML in an absolutely positioned way relative to the top left of the <foreignObject>)

How might we fix this? Does this have to wait for browser implementors?

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<svg width="960" height="300">
<g transform="translate(50,150)">
<circle r="6" />
<foreignObject style="overflow: visible;" width="1" height="1">
<div style="background: #f00; width: 100px; height: 100px;"></div>
</foreignObject>
</g>
<g transform="translate(200,150)">
<circle r="6" />
<foreignObject style="overflow: visible;" width="1" height="1">
<div style="position: relative;">
<div style="position: absolute; top: 10px; left: 10px; width: 100px; height: 100px; width: 100px; height: 100px; background: #0ff;">
</div>
</div>
</foreignObject>
</g>
<g transform="translate(350,150)">
<circle r="6" />
<foreignObject style="overflow: visible;" width="1" height="1">
<div style="transform: translate(20px, 20px);">
<div style="width: 100px; height: 100px; width: 100px; height: 100px; background: #00f;">
</div>
</div>
</foreignObject>
</g>
</svg>
<div style="position: relative">
<div style="position: absolute; top: 100px; left: 50px; background: #000; width: 12px; height: 12px; border-radius: 6px;">
<div id="tooltip" style="position: absolute; bottom: 30px; left: 0px; background: #eee; padding: 5px;">
<p style="width: 120px; line-height: 1; margin: 0;">&hellip;but I just want to be a tooltip!</p>
</div>
</div>
</div>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment