如何设置Office Fluent UI Modal居中显示在可视窗口?
Got it, let's tackle that frustrating Modal centering issue! The problem here is that by default, the Fluent UI Modal renders within the same component tree as your DocumentCard. If that parent container (the one holding all your DocumentCards) is a long scrollable list, the Modal will center relative to that container—forcing you to scroll to see it.
Here's the simple fix: tell the Modal to mount directly to the document.body instead of its parent component. This makes it center relative to the visible viewport, no scrolling required.
Modified Code Snippet
return ( <DocumentCard onClick={showModal}> <DocumentCardTitle title={this.props.Title} shouldTruncate /> <Image {...imageProps} className={styles.image} /> <DocumentCardTitle title={this.props.event.Description} shouldTruncate showAsSecondaryTitle /> {/* Add layerProps to mount Modal to document.body */} <Modal isOpen={isModalOpen} onDismiss={hideModal} isBlocking={true} layerProps={{ target: document.body }} > <div> <span id={titleId}>{this.props.Title}</span> </div> <div> <p>{this.props.event.Description}</p> </div> </Modal> </DocumentCard> );
How This Works
The layerProps prop passes configuration to the underlying Fluent UI Layer component, which handles where the Modal is rendered. By setting target: document.body, we detach the Modal from its scrollable parent container and attach it to the top-level body element. This ensures the Modal's positioning is calculated relative to the entire browser viewport, so it stays centered no matter where you are in the scroll list.
Bonus: Fine-Tuning Positioning
If you need even more control over the Modal's placement, you can add custom styles via rootProps inside layerProps:
layerProps={{ target: document.body, rootProps: { style: { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', // Add any other custom positioning styles here } } }}
But in most cases, just setting target: document.body will solve the issue cleanly.
内容的提问来源于stack exchange,提问作者Martin Hatch

