~ 2 min read
Parallax Scrolling with Astro

Parallax Scrolling Effect with Astro
Astro makes it easy, as we can add all the Div’s and the script into one .astro component, then call it in the index.astro without worrying about HTML components.
I’ve found it easiest to use Vanilla JS with Astro. Other JavaScript Frameworks, such as officially supporting Astro Integrations, will also work but add a level of complexity that is not required.
The expected results of this implementation should look similar to the astronaut that scrolls alongside the Home Page when a desktop.
Inspiration
First Found on Amelite, then reverse engineered and personalized for my implementation.
Create Parallax Component
If you are not using @astrojs/image, you can use the IMG tag and modify your code appropriately or add it by navigating to your project directory in the Command Line and using Requirements
npm i @astrojs/images
parallax.astro
---
import Picture from '@astrojs/image';
---
<div class="scroll" data-speed="3.9">
<Picture src={import('~/assets/images/flyguy.webp')} widths={[100]} aspectRatio={0.47} class="flyGuy" alt="flyguy" />
</div>
<script type="module">
function enableParallax() {
const isMac =
navigator.userAgentData?.platform.toLowerCase().includes('mac') ||
navigator.platform?.toLowerCase().includes('mac');
const isChrome = navigator.userAgent.toLowerCase().includes('chrome');
// Laggy behavior on chrome and mac with parallax scrolling
if (isMac && isChrome) return;
const targets = document.querySelectorAll('.scroll');
window.addEventListener('scroll', () => {
const offset = window.scrollY / 10;
targets.forEach((target) => {
target.style.transform = `translateY(${offset * target.dataset.speed}px)`;
});
});
}
enableParallax();
</script>
Add CSS Styling
base.css
.scroll {
position: fixed;
left: 0;
z-index: 1;
}
.flyGuy {
transform: rotate(81deg);
top: 0.5rem;
z-index: 1;
}
Use Parallax Component
Import and call your component on your index or other pages index.astro
---
import Parallax from "locationof/parallax.astro"
---
<Parallax />