模态框内容溢出父框架,.inner设置百分比高度不生效问题求解
问题根因
- CSS中百分比高度要生效,要求父元素必须有明确的可计算高度值,你当前的结构层级是
.modal_form→.modal_content→.inner:.modal_form只设置了max-height: 80%,没有声明固定高度,子元素无法基于它计算百分比高度.modal_content也没有设置高度,默认是内容撑开高度,.inner的80%高度找不到参考基准,所以不生效
- 你要实现「内容区滚动+按钮固定底部」的布局,没有给父容器设置空间分配规则,内容多了自然就会溢出整个模态框。
修复方案(仅需修改CSS部分即可)
.modal { display: none; width: 100%; height: 100%; z-index: 2; position: absolute; top: 0; left: 0; background-color: rgba(20, 20, 20, 0.6); padding: 1em 2em; box-sizing: border-box; /* 新增:避免padding把容器撑宽超出屏幕 */ } .modal_form { z-index: 3; background: rgba(200, 200, 210, 1); border: 1px solid black; border-radius: 10px; width: fit-content; max-width: 80%; position: relative; top: 50%; transform: translateY(-50%); padding: 1em 2em; margin: 0 auto; max-height: 80%; overflow: hidden; display: flex; /* 新增:改为flex布局,自动分配内容区和按钮区的高度 */ flex-direction: column; /* 新增:垂直排列子元素 */ } .modal_content { width: fit-content; margin: 1em auto 1em auto; display: flex; flex-direction: column; flex: 1; /* 新增:占满modal_form除了按钮区之外的所有剩余高度 */ min-height: 0; /* 新增:兼容flex布局下内容溢出时的高度限制逻辑 */ } .inner { overflow: auto; flex: 1; /* 替换原有的height:80%,自动占满modal_content除标题外的高度 */ } /* 原有样式无需修改 */ .modal_content table {} .m_btn { background: #ddd; border: 1px solid black; padding: 0.3em 1em; border-radius: 5px; box-shadow: 3px 3px 5px grey; } /* 可选:给按钮区加上边距,样式更美观 */ .modal_btns { margin-top: 1em; text-align: center; }
修改说明
调整后.modal_form会用flex布局自动分配空间,内容区高度会自适应模态框高度,内容超出时自动出现滚动条,不会溢出模态框,按钮也会固定在模态框底部,不需要手动计算高度百分比。
内容的提问来源于stack exchange,提问作者DenisSh
相关产品推荐
相关产品推荐

