如何为Material-UI Tooltip指定document.body作为容器元素?
document.body Got it, let's tackle this Tooltip clipping issue you're facing. The problem here is that when your reference element is stuck inside a narrow (60px wide) container with overflow:hidden, the Tooltip gets rendered as a sibling element inside that same container—so it gets cut off just like any overflowing content.
Just like how Bootstrap lets you route the Tooltip to the body to avoid this, Material-UI has a straightforward way to do the same. We can leverage the PopperProps prop (since Material-UI Tooltip uses Popper under the hood) to mount the Tooltip directly to document.body, pulling it out of the constrained container entirely.
Here's a concrete example to implement this:
import Tooltip from '@mui/material/Tooltip'; import Button from '@mui/material/Button'; const NarrowContainer = () => ( <div style={{ width: '60px', overflow: 'hidden', border: '1px solid #ccc' }}> <Tooltip title="This long tooltip won't get clipped anymore!" placement="left" // Ensures the Tooltip points left toward the reference element PopperProps={{ // This is the critical line to attach the Tooltip to document.body container: document.body, // Optional: Adjust popper behavior if you want to force left placement popperOptions: { modifiers: [ { name: 'flip', enabled: false }, // Disable automatic placement switching { name: 'preventOverflow', enabled: false } // Ignore viewport boundary checks ] } }} > <Button size="small">Hover Me</Button> </Tooltip> </div> ); export default NarrowContainer;
Key Details:
PopperProps.container: This prop tells Material-UI to render the Tooltip's content intodocument.bodyinstead of the same container as the reference element. This removes it from theoverflow:hiddencontext, so it won't get clipped.placement="left": Explicitly sets the Tooltip to appear to the left of the reference element, matching your requirement to have it point toward the element.- Optional modifiers: The
flipandpreventOverflowmodifiers can be disabled if you want to force the left placement, even if there's limited space on that side. Enable them if you want the Tooltip to automatically adjust its position to stay visible.
A quick note: If you run into z-index issues (where other elements overlay the Tooltip), you can adjust it with the sx prop on the Tooltip, like sx={{ zIndex: 1300 }} (Material-UI's default Tooltip z-index is 1300, tweak as needed for your layout).
内容的提问来源于stack exchange,提问作者aegyed

