react-modal组件弹窗无法水平垂直居中如何解决
问题根源
你的代码有两个直接导致定位失效的问题:
- CSS属性值写法错误:你在
.modal样式中给top、left、transform等属性的取值额外包裹了单引号,这种写法仅适用于JSX内联样式、CSS-in-JS场景,写在独立SCSS/CSS文件中时属性值不能加引号,浏览器会直接判定这些CSS规则无效,定位逻辑完全不生效,弹窗就会默认停在左上角。 - 冗余定位属性干扰:
margin-right: '-50%'是早年兼容IE低版本的居中hack,现代浏览器下配合transform: translate(-50%, -50%)实现居中不需要这个属性,保留反而会造成位置偏移。
另外你的遮罩层样式缺少层级声明,容易被页面其他元素遮挡,建议补充z-index属性。
修正后可直接运行的代码
组件部分
<main className={styles.main}> <Modal isOpen={isShowModal} className={styles.modal} overlayClassName={styles.overlay} ariaHideApp={false} contentLabel='example modal' // 若需要将弹窗挂载到当前main节点下而非默认的body根节点,可取消下一行注释 // parentSelector={() => document.querySelector(`.${styles.main}`)} > Here is some modal content!<br/> Here is some modal content!<br/> Here is some modal content!<br/> Here is some modal content!<br/> Here is some modal content!<br/> </Modal> </main>
样式部分
.main { height: $page-height; background: $sea-lord-background; padding: 20px 20px; } .modal { position: absolute; // 移除所有属性值的多余单引号 top: 50%; left: 50%; right: auto; bottom: auto; // 删除冗余的margin-right属性 transform: translate(-50%, -50%); background-color: $gray; opacity: 0.6; // 建议设置固定宽高和内边距,避免内容撑开导致定位异常、内容贴边 // width: 500px; // min-height: 300px; // padding: 24px; } .overlay { position: fixed; inset: 0; // 等价于top/left/right/bottom全设为0,写法更简洁,兼容低版本浏览器可换回四个方向的单独声明 background-color: lime; // 补充高层级避免被页面其他元素遮挡 z-index: 999; }
内容的提问来源于stack exchange,提问作者RobertW
相关产品推荐
相关产品推荐

