使用 absolute 定位和 transform 可实现模态框水平垂直居中。1. 设置父容器为 relative 或 fixed,子元素为 absolute;2. 模态框设置 top: 50%、left: 50%;3. 再通过 transform: translate(-50%, -50%) 向左上移动自身宽高一半,实现精准居中,无需知道具体尺寸,适用于动态内容弹窗,兼容性好且简洁可靠。
使用 absolute 定位和 transform 可以非常灵活地实现模态框在页面中水平垂直居中,尤其适用于不知道模态框具体尺寸的场景。
提示
这是一个居中的模态框
.modal-container {
position: fixed;
top: 0;
l
eft: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
width: 300px;
text-align: center;
}
其中核心是这三行:
基本上就这些,简单有效,兼容性好,现代项目中广泛使用。