惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
H
Help Net Security
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Full Disclosure
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
T
Tenable Blog
T
Tor Project blog
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
B
Blog
V
V2EX
Jina AI
Jina AI
L
LangChain Blog
月光博客
月光博客
W
WeLiveSecurity
U
Unit 42
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
V
Visual Studio Blog
A
Arctic Wolf
T
Tailwind CSS Blog
The Cloudflare Blog
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
www.infosecurity-magazine.com
www.infosecurity-magazine.com
腾讯CDC
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
A sticky parallax hero in twenty lines of JS
Ivo Jerkovic · 2026-05-20 · via DEV Community

Where the idea came from

A few weeks ago someone asked on a forum how to recreate the Mammut hero — the one where a full-screen image pins to the viewport while text scrolls up over it. They called it "a simple, I think, parallax question."

Kind of! The Mammut hero is the type of effect that looks like one thing and turns out to be three things stacked. GSAP or Locomotive Scroll handle it beautifully, but it's also doable with position: sticky and twenty lines of JavaScript — handy when you don't want to pull in a whole library for a single hero.

I haven't built this on a real client project yet — the thread just made me curious enough to break it down. What follows is the version I'd share if someone asked me how to do it: the same composition Mammut uses, simplified down to the load-bearing primitives, plus a few small bits of production polish to round it out. Plain HTML and CSS, no framework needed. Live demo lives in the lab.

Three layers, not one

The illusion you're seeing on mammut.com is built from:

  1. A sticky-positioned container that pins to the viewport.
  2. An image inside it that translates slightly while pinned — the parallax-within-pin.
  3. A text block placed after the sticky container in the DOM, which scrolls up at normal speed and passes over the pinned image.

The whole thing is wrapped in an outer block whose height determines how long the hero stays pinned. When that outer block's bottom hits the viewport bottom, the sticky element releases and the page continues normally.

That structure is the whole trick. Everything else is decoration.

The markup

<section class="hero-block">
  <!-- 1. The pinned container -->
  <div class="hero-sticky">
    <div class="hero-image"><img src="..." alt="..."></div>
    <div class="hero-title">
      <h1>Senior dev in the room.</h1>
    </div>
  </div>

  <!-- 2. The text that scrolls over -->
  <div class="hero-text">
    <p>Ivo Jerković is a full-stack developer…</p>
  </div>
</section>

Enter fullscreen mode Exit fullscreen mode

The .hero-image and .hero-title are inside the sticky container so they get pinned along with it. The .hero-text is a sibling of .hero-sticky, sitting after it in the DOM. That ordering is what makes the text appear to scroll up over the image: as the user scrolls, the sticky element holds its position, and the text below comes up into view.

The CSS that does the work

.hero-block {
  position: relative;
  background: #000;
}

.hero-sticky {
  position: sticky;
  top: 0;
  height: 100vh;
  overflow: hidden;
}

.hero-image {
  position: absolute;
  top: -50px;
  left: 0;
  width: 100%;
  height: calc(100% + 300px);  /* slack for the translation */
  will-change: transform;
}
.hero-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero-text {
  position: relative;
  max-width: 600px;
  margin: 0 0 0 auto;
  padding: 80vh 48px 80vh;     /* this padding is the hero's "duration" */
  color: white;
}

Enter fullscreen mode Exit fullscreen mode

Two non-obvious details:

The image needs vertical slack. It gets top: -50px and height: calc(100% + 300px) so that when JS translates it upward by ~20% of the viewport height, no background shows through at the bottom edge. The slack budget has to be greater than the maximum translation distance.

The text padding is the scroll duration. That padding: 80vh 48px 80vh on .hero-text is what gives the hero its length. Make the padding taller and the image stays pinned longer. Make it shorter and the hero releases faster. There's no "scroll length" property to set — the height of the text block (plus padding) determines everything.

The JS — twenty lines

const block = document.getElementById('hero-block');
const image = document.querySelector('.hero-image');
const title = document.querySelector('.hero-title');

function update() {
  const rect = block.getBoundingClientRect();
  const vh = window.innerHeight;

  // Progress 0..1 across the block.
  // 0 = block top just locked to viewport top.
  // 1 = block bottom reached viewport bottom (about to release).
  const total = block.offsetHeight - vh;
  const scrolled = -rect.top;
  const progress = Math.max(0, Math.min(1, scrolled / total));

  // Translate as a fraction of viewport height, not pixels —
  // so the effect scales with screen size.
  image.style.transform = `translate3d(0, ${progress * vh * -0.18}px, 0)`;
  title.style.transform = `translate3d(0, ${progress * vh * -0.10}px, 0)`;
}

update();
window.addEventListener('scroll', update, { passive: true });

Enter fullscreen mode Exit fullscreen mode

The whole "parallax" effect is one number: progress, a value between 0 and 1 representing how far through the sticky block the user has scrolled. Image moves 18% of viewport height across the whole sticky lifetime; title moves 10% — slightly faster relative motion, giving the depth cue.

That's the basic demo. It works — and for plenty of use cases, that's all you need. Three small additions make it production-friendly.

Three things to add before shipping

1. The scroll listener fires too often

update() runs on every single scroll event. On a 120Hz display, that can be 120 calls per second. The math is cheap but the layout reads (getBoundingClientRect, offsetHeight) are not — each one can force a layout if a previous frame queued style changes.

Wrap it in requestAnimationFrame with a ticking flag:

let ticking = false;
function onScroll() {
  if (ticking) return;
  ticking = true;
  requestAnimationFrame(() => {
    update();
    ticking = false;
  });
}
window.addEventListener('scroll', onScroll, { passive: true });

Enter fullscreen mode Exit fullscreen mode

Now update() runs at most once per animation frame. On a 120Hz display that's still 120fps of smooth animation but you've stopped re-doing work between paints.

2. No prefers-reduced-motion handling

Some visitors have their OS set to "reduce motion" — parallax effects can be physically nauseating for them. Honor the preference and skip the translations:

const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function update() {
  // …progress math…
  const imageY = reduce ? 0 : progress * vh * -0.18;
  const titleY = reduce ? 0 : progress * vh * -0.10;
  // …
}

Enter fullscreen mode Exit fullscreen mode

The image still pins (that's a layout thing, not a motion thing) — only the drift is suppressed. The pinned-and-static version still reads correctly as a hero.

3. The listener runs even when the hero is off-screen

Once the user has scrolled past the hero, the update() math keeps running on every scroll for the rest of the page. Wasted work. Gate the listener with an IntersectionObserver:

let inView = false;
const io = new IntersectionObserver(([entry]) => {
  inView = entry.isIntersecting;
}, { rootMargin: '50% 0px' });
io.observe(block);

function onScroll() {
  if (!inView || ticking) return;
  // …
}

Enter fullscreen mode Exit fullscreen mode

The rootMargin: '50% 0px' keeps the observer "active" for half a viewport of slack above and below the hero, so the math fires just before and just after the hero is visible — no flicker.

A few gotchas worth knowing about

iOS Safari and sticky inside transformed parents. If any ancestor of .hero-sticky has a transform, filter, will-change, or perspective other than none, sticky positioning breaks — silently. The element stops pinning. If your hero "kind of works on desktop but does nothing on iPhone," this is almost always why. Audit the parent chain.

backdrop-filter does the same thing. Burned me on this exact site — the header had backdrop-filter: blur(8px) and a fixed-position drawer inside it was being clipped to the header's box instead of the viewport. Same root cause: backdrop-filter establishes a containing block for fixed and sticky descendants.

The image-slack math is brittle. If you ever change the max translation in JS (say from 18% to 30% of viewport height), the CSS height: calc(100% + 300px) may no longer be enough slack — 30% of a 1080px desktop viewport is already 324px, over budget. Safer to express the slack as a function of viewport in CSS too: height: calc(100% + 25vh) keeps the two in lockstep.

object-position: center is fine until you have a tall vertical image on a wide landscape viewport, or vice versa. Then your subject ends up cropped weirdly. For hero images that need a specific focal point, set object-position to a fraction (50% 30%) and pick it deliberately per image.

Why I went vanilla here

Most posts about parallax heroes start with an animation library, and that's a great call when you need timeline orchestration or scroll-driven sequences. GSAP especially is hard to beat once the choreography gets complex. For this specific effect — a hero that pins and drifts — position: sticky and transform are already doing most of the work, so a library would mostly be along for the ride.

Twenty lines of vanilla JS, four CSS rules, and a clear mental model of what each layer is doing. That's the whole thing. The forum poster who asked the question had it right when they called it "simple" — once the three primitives are named, it really is.

Originally posted at ivojerkovic.com.