用 Flex 实现遮罩层+居中弹窗的核心是:遮罩层设 position: fixed + display: flex + justify-content/align-items: center 实现全屏覆盖与居中,弹窗无需绝对定位即可被父容器居中,配合背景、圆角、阴影提升视觉效果。
用 Flex 实现遮罩层+居中弹窗,是 CSS 新手非常实用且易掌握的方案。核心就两点:让遮罩占满全屏、让弹窗在其中绝对居中——而 Flex 的 justify-content 和 align-items 能一行代码搞定垂直水平居中,比传统定
位清晰得多。
遮罩层(通常叫 .modal-overlay)需要覆盖整个视口,且不随滚动条移动:
position: fixed,四边为 0(top/right/bottom/left: 0)display: flex,并设置 justify-content: center(水平居中)和 align-items: center(垂直居中)background-color: rgba(0,0,0,0.6),提升视觉层次弹窗(如 .modal-box)直接放在遮罩层内部,不用写 position: absolute 或 transform: translate(-50%, -50%):
width: 90%; max-width: 400px; padding: 24px;),避免过小或撑满background: #fff、圆角 border-radius: 8px 和阴影 box-shadow: 0 4px 12px rgba(0,0,0,0.15),看起来更像模态框结构要简洁,遮罩层包裹弹窗,初始隐藏(用 display: none 或类控制显隐):
这是一个居中的弹窗
点击按钮显示遮罩和弹窗,点遮罩或关闭按钮隐藏它(注意:只隐藏遮罩,不删除 DOM):
display: flex 显示,移除则设为 display: none
event.target === overlay,避免点弹窗内容也关闭Esc 键也能关闭:document.addEventListener('keydown', e => e.key === 'Escape' && overlay.style.display = 'none')