HTML/CSS实现的弹窗内容增加时顶部内容消失问题求助
问题根因
你遇到的顶部内容消失问题是popup__content的垂直居中方案导致的:
你当前用position: absolute + top: 50% + transform: translateY(-50%)做垂直居中,当弹窗内容高度超过视口高度时,translateY(-50%)会把内容整体向上拉自身高度的一半,直接导致内容顶部超出视口上边界,且超出的部分无法通过滚动展示。
另外还有两个加重问题的细节:
popup__content设置了overflow: hidden,会直接裁剪超出容器的内容popup__content的padding只写在:target触发态里,初始状态无padding,触发后才新增padding会导致高度计算偏差,过渡动画也会出现跳动
修复方案
按以下步骤修改CSS即可解决:
- 给父容器
.popup改用flex布局做居中,替代原有绝对定位居中方案 - 移除
popup__content的绝对定位相关属性、overflow: hidden、display: table配置 - 把
padding从:target状态移到popup__content基础样式中,统一高度计算 - 给
popup__content增加最大高度限制,内容超出时内部可滚动
修改后的完整CSS如下:
/* Pop up */ .popup { height: 100vh; width: 100%; position: fixed; top: 0; left: 0; background-color: rgba(0, 0, 0, 0.8); z-index: 3000; /* 新增flex居中配置 */ display: flex; justify-content: center; align-items: center; /* 内容超过视口时父级可滚动,适配小屏设备 */ overflow-y: auto; /* 给上下留边距,避免内容贴顶贴底 */ padding: 2rem 0; box-sizing: border-box; opacity: 0; visibility: hidden; -webkit-transition: all 0.3s; transition: all 0.3s; } @supports ( (-webkit-backdrop-filter: blur(10px)) or (backdrop-filter: blur(10px))) { .popup { -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); background-color: rgba(0, 0, 0, 0.3); } } .popup .header__logo-box { height: 100px; /* 移除原有的margin-top,交给父级flex居中控制 */ } .popup__content .heading-secondary { font-size: 2rem; } .popup__content .heading-tertiary { font-size: 1.5rem; } .popup__content { /* 移除原有绝对定位、transform、display: table、overflow: hidden */ width: 50%; background-color: #fff; -webkit-box-shadow: 0 2rem 4rem rgba(0, 0, 0, 0.2); box-shadow: 0 2rem 4rem rgba(0, 0, 0, 0.2); border-radius: 3px; opacity: 0; /* 修改变换属性,只保留缩放效果 */ transform: scale(0.25); -webkit-transition: all 0.5s 0.2s; transition: all 0.5s 0.2s; text-align: center; /* 把padding移到基础样式中 */ padding: 3rem; box-sizing: border-box; /* 新增最大高度限制,超出内部滚动 */ max-height: 90vh; overflow-y: auto; } .popup:target { opacity: 1; visibility: visible; } .popup:target .popup__content { opacity: 1; /* 修改变换属性,只保留缩放还原 */ transform: scale(1); } .popup__close:link, .popup__close:visited { color: #777; position: absolute; top: 1rem; right: 1rem; font-size: 3rem; text-decoration: none; display: inline-block; -webkit-transition: all 0.2s; transition: all 0.2s; line-height: 1; } .popup__close:hover { color: var(--color-secondary); } .popup__close--pp:link, .popup__close--pp:visited { color: #777; position: absolute; top: 13rem; right: 2rem; font-size: 3rem; text-decoration: none; display: inline-block; -webkit-transition: all 0.2s; transition: all 0.2s; line-height: 1; } .popup__close--pp:hover { color: var(--color-secondary); } .popup__text { text-align: left; font-size: 1.2rem; }
额外优化建议
你当前的.popup__close--pp的top是固定的13rem,内容高度变化时位置会错位,建议改为top: 1rem,和通用关闭按钮保持一致,避免超出可视区域。
内容的提问来源于stack exchange,提问作者Himat Varsani
相关产品推荐
相关产品推荐

