滚动至顶部固定导航栏时内容渐隐效果-webkit-gradient实现失效
问题原因
- 遮罩挂载对象完全错误:
mask-image(含webkit前缀版本)的作用是控制挂载该属性的元素自身的透明度,你把遮罩加在.menu上,只会让菜单里的logo、汉堡按钮从顶部实到底部透,根本不会影响下方滚动的内容。另外你的.menu没有设置任何背景,本身就是全透明的,自然挡不住滚到导航区域的内容。 - 渐变方向写反:你定义的渐变是顶部不透明、底部透明,和需求完全相反。要实现内容靠近导航时淡出,需要的是靠近导航的位置遮罩不透明、远离导航的位置遮罩透明。
- 兼容性语法缺失:仅写了老旧的
-webkit-gradient私有语法,没有补充标准CSS mask属性,非Webkit内核浏览器无法识别该规则。
修正方法
两种实现方案都可以,按需选择即可:
方案1:渐变遮罩层(兼容性最好,所有主流浏览器都支持)
核心逻辑:给固定导航加和页面一致的固定背景,保证导航本身完全不透明、和页面背景无缝衔接;再在导航下方加一个同高的固定渐变层,层级高于滚动内容,内容滚到该区域时会被渐变层逐渐遮挡,实现淡出效果,渐变层设置pointer-events: none不会阻挡页面交互。
完整CSS代码:
.wrapper { background-image: url("https://amymhaddad.s3.amazonaws.com/morocco-blue.png"); background-attachment: fixed; min-height: 200vh; /* 保证页面有足够滚动空间 */ } .menu { position: fixed; width: 100%; z-index: 98; height: 80px; /* 导航设置和页面一致的固定背景 */ background-image: url("https://amymhaddad.s3.amazonaws.com/morocco-blue.png"); background-attachment: fixed; } /* 新增渐变遮罩层 */ .gradient-mask { position: fixed; top: 80px; left: 0; width: 100%; height: 80px; z-index: 97; /* 渐变从上到下从实到透,颜色和页面背景主色匹配即可 */ background: linear-gradient(to bottom, #e7edf1 0%, rgba(231, 237, 241, 0) 100%); pointer-events: none; } .hamburger { position: absolute; left: 30px; top: 30px; width: 50px; } .site-logo { position: absolute; right: 30px; top: 30px; width: 170px; } .content { padding-top: 160px; /* 留出导航+遮罩的高度,避免初始内容被遮挡 */ }
对应HTML调整,在menu后插入遮罩层即可:
<div class="wrapper"> <div class="menu"> <img class="hamburger" alt="menu" /> <div class="site-logo">Logo</div> </div> <div class="gradient-mask"></div> <div class="content"> <p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p><p>Example content</p> </div> </div>
方案2:直接给内容区加mask(代码更简洁)
不需要额外加DOM元素,直接给内容区加遮罩,让内容区顶部80px从透明过渡到不透明,透出后方的页面背景即可,注意要同时写标准属性和webkit前缀保证兼容性,同时必须给menu设置不透明背景,否则透明的内容会直接透过导航显示。
核心CSS代码:
.menu { position: fixed; width: 100%; z-index: 98; height: 80px; /* 必须给导航加不透明背景 */ background-image: url("https://amymhaddad.s3.amazonaws.com/morocco-blue.png"); background-attachment: fixed; } .content { padding-top: 100px; /* 内容区顶部渐变透明 */ -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 80px); mask-image: linear-gradient(to bottom, transparent 0, #000 80px); }
内容的提问来源于stack exchange,提问作者HNG
相关产品推荐
相关产品推荐

