乐闻世界logo
搜索文章和话题

How do you implement a CSS-only parallax scrolling effect?

1个答案

1

When implementing parallax scrolling effects using only CSS, we primarily leverage CSS properties to adjust the scrolling speed of background images, making them move at a different rate than the page content and thereby creating a parallax effect. Here is a basic implementation method:

  1. HTML Structure: First, set up the HTML structure. Typically, you have multiple sections, each containing a background with a parallax effect.
html
<div class="parallax-section"> <h1>Parallax Effect Area 1</h1> </div> <div class="content-section"> <p>This is the normal content area.</p> </div> <div class="parallax-section"> <h1>Parallax Effect Area 2</h1> </div>
  1. CSS Styles: Next, configure these parallax effects using CSS. Primarily, use the background-attachment property to fix the background image, preventing it from scrolling with the page.
css
.parallax-section { height: 300px; background-image: url('background-image-url.jpg'); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; }

By setting background-attachment: fixed;, the background image remains stationary while the page scrolls, creating a parallax effect relative to the content.

  1. Optimization and Compatibility: Although this approach is straightforward, it has compatibility issues, particularly on mobile devices. iOS Safari may encounter performance problems when handling background-attachment: fixed;. For better compatibility and performance, consider using JavaScript or other CSS3 features (such as transform) to achieve more complex parallax effects.

  2. Enhancing Parallax Effect with CSS Variables: Utilize CSS variables and the calc() function to dynamically adjust the background position based on scroll position, creating a more dynamic parallax effect.

css
:root { --scroll-var: 0px; } .parallax-section { height: 300px; background: url('background-image-url.jpg') center / cover no-repeat fixed; background-position: center calc(50% + var(--scroll-var)); } body { height: 2000px; } window.onscroll = () => { document.documentElement.style.setProperty('--scroll-var', `${window.scrollY / 2}px`); }

Note: The JavaScript implementation has been corrected to window.onscroll for proper functionality. This method provides a basic approach for pure CSS parallax scrolling, suitable for simple scenarios. For more complex effects, JavaScript integration may be necessary.

2024年7月26日 13:51 回复

你的答案