You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS Parallax视差效果仅背景图生效 文本滚动异常问题

问题原因

你当前实现的视差效果仅作用于背景图:#parallax容器设置的background-attachment: fixed只会让背景图相对于视口固定,容器本身和内部的文本都属于正常文档流,默认会跟随页面滚动,不会自动产生视差差速。
另外你的代码存在3处影响效果的冗余/错误:

  • .intro-text重复声明了两次width: 100%,属于无效冗余代码
  • <nav class="navbar";>标签末尾多写了分号,存在HTML语法错误
  • 给.intro-text设置的background-attachment: initial无实际作用,该属性仅对设置了背景图的元素生效
修复方案

纯CSS无法实现文本和页面滚动的差速视差,需要搭配少量JS监听滚动事件,通过transform给文本设置不同的滚动速率,实现流畅的视差效果,修正后的可直接复用代码如下:

修正后的CSS代码

*{
    box-sizing: border-box;
}
body{
    margin: 0;
    background-color: #ffffff;
}

ul{
    text-align: center;
    padding: 0 20px;
    margin: 12px auto;
    list-style: none;
    position: fixed;
    z-index:10;
    top: 0;
    width: 100%;
    left: 0;
}

ul, li{
    display: inline-table;
}

li{
    margin: 10px 30px;
    font-size: 15px;
    color: #42385d;
    font-weight: bold;
    font-family: 'Roboto Slab', serif;
}


.navbar{
    background-color: #ffcfda;
    position: fixed;
    width: 100%;
    border-bottom: 1px solid #ffcfda;
    z-index: 10;
    height: 70px;
    top: 0;
    overflow: hidden;
}

#parallax{
    background-image: url("pinkbackground.jpg");
    min-height: 100vh;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    position: relative;
}

.intro-text{
    text-align: center;
    width: 100%;
    color: #42385d;
    padding: 37vh 0;    
    height: 100vh;
    font-size: 50px;
    font-family: 'Roboto Slab', serif;
    position: absolute;
    top: 0;
    left: 0;
    will-change: transform;
}

.transition{
    height: 200px;
    background-color: #42385d;
    width: 100%;
}

.question{
    font-size: 30px;
    font-family: 'Roboto Mono', monospace;   
    color: #42385d;
    font-weight: bolder;
    padding-top: 40px;
}

新增JS逻辑(放置在</body>标签前即可)

const parallaxText = document.querySelector('.intro-text');
// 0.5为文本滚动速率,数值越小文本移动越慢,视差层次感越强,可按需调整
window.addEventListener('scroll', () => {
    const offset = window.pageYOffset;
    parallaxText.style.transform = `translateY(${offset * 0.5}px)`;
})

HTML修正点

删除nav标签上多余的分号,原错误写法<nav class="navbar";>改为:

<nav class="navbar">

如果你不需要差速效果,只想让文本和背景图一样完全固定在视口上,不需要加JS,直接给.intro-text设置position: fixed即可,这种方式实现简单,但没有滚动差速的层次感。

内容的提问来源于stack exchange,提问作者Naol Wordoffa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 02:21:18