带border、padding、margin的DIV水平垂直居中,窗口缩放下边框挡文字如何解决
DIV垂直居中底部边框遮挡内容修复方案
问题原因
遮挡问题由两个属性配置不合理导致:
.main设置了max-height: 80vh但未配置溢出处理规则,内容超出容器高度时默认溢出到边框外,被边框遮挡- 父容器
.wrap的align-items: center在视口高度极小的场景下,会导致居中的子元素上下部分被视口裁剪,看不到顶部/底部内容
修复方案
修改CSS规则即可解决,完全保留你要求的border/padding/margin属性:
- 给
.main添加overflow-y: auto,内容超出高度时自动出现纵向滚动条,不会溢出边框范围 - 调整
.main的max-height为min(80vh, calc(100vh - 40px)),既保留原有的80vh最大高度逻辑,又在小视口场景下自动适配视口高度,减去上下20px的margin值避免整体超出视口 - 将
.wrap的align-items改为safe center,保证子元素高度超过父容器时不会被强制裁剪,始终可以滚动查看完整内容
修改后的完整CSS代码:
div.wrap { align-items: safe center; bottom: 0; display: flex; justify-content: center; left: 0; position: fixed; right: 0; top: 0; } div.main { border: 1px solid red; margin: 20px; padding: 20px; display: flex; flex-direction: column; max-height: min(80vh, calc(100vh - 40px)); max-width: 300px; width: 100%; overflow-y: auto; }
老旧浏览器兼容方案
如果需要兼容不支持min()函数和safe关键字的浏览器,可以使用以下替代方案,效果一致:
div.wrap { bottom: 0; display: flex; justify-content: center; left: 0; position: fixed; right: 0; top: 0; } div.main { border: 1px solid red; margin: auto 20px; padding: 20px; display: flex; flex-direction: column; max-height: calc(100vh - 40px); max-width: 300px; width: 100%; overflow-y: auto; }
内容的提问来源于stack exchange,提问作者Miguel Moura
相关产品推荐
相关产品推荐

