Create a type of parallax effect where the text block is fixed in place, similar to a background-attachment

In my quest to create a unique parallax effect, I am exploring the idea of making each section scroll vertically to unveil the next one, with distinct background colors, images, and text blocks. The challenge lies in keeping the text fixed relative to its parent container while achieving this effect.

To visualize what I aim to achieve, I have created a static example using screenshots for each section: static example. However, my goal is to make the content dynamic rather than relying on flat images.

Below is a simplified version of the code I have written so far:

Code snippet here...

The parallax effect is implemented through CSS utilizing background-attachment: fixed, which functions correctly. However, the issue arises with positioning the text blocks. My intention is to have them remain stationary within their respective sections while centered. When set to position: fixed, the text elements overlap or all display at once in the initial section. Alternatively, any other position attribute causes them to scroll like standard elements.

I understand that setting an element's position to fixed removes its relation to the parent element flow; yet, I am searching for a solution involving advanced CSS techniques or even a JavaScript alternative to accomplish this desired effect.

I have experimented with various HTML/CSS structures and attempted multiple JavaScript solutions such as rellax, jarallax, and ScrollMagic, but these options are too complex for my requirements. Despite dedicating ample time to searching for examples matching my concept, I have been unable to find a suitable one thus far.

Answer №1

Previously, I experimented with a similar effect involving images and JavaScript. This time, I decided to use the same technique but with text content instead of images. As it turns out, there doesn't seem to be a pure CSS solution for this, so I'm simulating the fixed position by dynamically adjusting the top property using absolute positioning.

Below is an example where I've made some adjustments to the CSS to simplify things. Additionally, CSS variables are used extensively to keep the JavaScript code minimal and manageable through CSS.

window.onscroll = function() {
  var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
  document.documentElement.style.setProperty('--scroll-var', scroll + "px");
}
:root {
  --scroll-var: 0px
}

body {
  margin: 0;
  padding: 0;
}

h2 {
  font-size: 48px;
}

p {
  font-size: 18px;
}

/* CSS styles for sections go here */

.content {
  /* Content styling */
}

.copy {
  color: #fff;
  font-family: 'Noto Serif', serif;
  font-weight: 300;
  max-width: 300px;
}

.button {
  /* Button styling */
}

.button:hover {
  /* Hover effect for button */
}
<body>
  <section class="first">
    <div class="content">
      <div class="copy">
        <h2>Header 1 </h2>
        <p>Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p>
      </div>
    </div>
  </section>
  <section class="second">
    <div class="content">
      <div class="copy">
        <h2>Header 2</h2>
        <p>Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p>
      </div>
    </div>
  </section>
  <section class="third">
    <div class="content">
      <div class="copy">
        <h2>Header 3</h2>
        <p>Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p>
      </div>
    </div>
  </section>
  <section class="fourth">
    <div class="content">
      <div class="copy">
        <h2>Call to action</h2>
        <a class="button">Button</a>
      </div>
    </div>
  </section>
</body>

Answer №2

If you're looking to master the art of positioning elements on a webpage, I've got just the snippet for you. It's functional, but the real challenge lies in understanding the mathematical intricacies behind it. Pay attention to the details and unleash your creativity!

$( document ).ready(function() {
    $(document).scroll(function() {
      // Determining the position of the first slide for accurate movement tracking
      var rect = $(".first")[0].getBoundingClientRect();
      
      // Calculating the viewport height
      var screenHeight = $( window ).height();
      
      // Defining the offset for every .copy element to maintain consistent top alignment
      // Your task: Unravel the precise math required here
      $(".copy").offset({ top: screenHeight*1.5-rect.bottom});
    });
});
Your CSS goes here...
Your HTML structure can be found above :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing an "isTrusted" error while working with the GLTFLoader

QUERY: All was running smoothly: I successfully transformed my FBX files to GLTF in the /GLTF/ directory. Unfortunately, after noticing missing geometry in some converted files, I attempted another conversion of the FBX files, this time to /TEST/. Unexp ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

Issue with event handling when using the `this` keyword in function

What is causing the this keyword to return undefined in the event handler and how can this issue be resolved? twittyApp.factory('Unshown', function () { function Unshown() { this.allIsLoaded = false; this.loading = false; this.firstT ...

Unable to retrieve the data-id from the ajax response for extraction and transfer to the modal

I am encountering an issue when trying to retrieve the data-id from an AJAX response within a href tag. The response always returns as undefined. $("#loader_ekpresi").show(); $.ajax({ url:"<?php echo site_url() ?>Home/get_ekspresi", type:& ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

What is the method for executing a function enclosed within a variable?

As someone new to the world of Java, I have encountered a puzzling issue with some code related to a game. Specifically, there seems to be an obstacle when it comes to utilizing the navigator function. When I click on this function in the game, some sort o ...

Linking input to radio buttons in Vue.js

When creating an edit form page, I encountered an issue where the page was not loading properly. Before the page loaded, I ran the following code: beforeMount(){ if(this.$route.meta.mode === 'edit'){ this.initialize = '/api/arti ...

Can an object be transformed into a new object by destructuring in ES6?

Consider the following scenario where an object named payload is defined: const payload = { apple: 1, dog: 2, cat: 3 } The goal is to destructure this object into a new one that contains only apple and dog: const newPayload = { apple: 1, ...

Ways to dynamically alter the appearance of a conditionally displayed element in Svelte

Currently experimenting with SvelteKit 1.0 by building a simple to-do app, but I'm having trouble implementing conditional text strikethrough. My goal is to have the text style change to include a strikethrough when the user clicks on the checkbox nex ...

My React project is not showing the text in the way that I had envisioned

When using the Material UI TextInput component with a placeholder prop set to display the text "Contraseña", I encountered an issue where the letter ñ was not rendering correctly and instead showing as \fx1. My HTML head section includes m ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

The length of JSON data retrieved may vary between Internet Explorer and Firefox

After receiving JSON data from the server via AJAX, I proceeded to evaluate it as follows: request.responseText=[{name:xxx},{name:yyy},{name:zzz}]. I then used the following code snippet: var data=eval(request.responseText); alert(data.length); Surpri ...

The background hue does not cover the entire element

When I hover over my drop-down menu button, the grey color only covers up to where I set the padding. Here is my HTML snippet: Help ▾ Give Get Help Get Involved I want the grey color to expand fully across the "li" ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Slideshow with Jquery featuring image transitions from left to right and elegant fade-in effects

I am trying to create a unique slideshow effect with 6 graphics. The first two graphics should slide from left to right, the third graphic should fade in and stick, and then the remaining graphics should slide from left to right. I have been able to impl ...

What are the steps for utilizing a map created by an exorcist?

Keep in mind that I am new to this, so I may be overlooking something obvious. Generating a .map with exorcist during the creation of a Browserify bundle is straightforward if you follow the guidelines on the official website. But once you have the resul ...

What is the best way to make this row div vertically stretch to match the width of its container in Bootstrap 4?

When I use class="col", it reduces the table width and since there are many columns, each centimeter counts. If I switch to class="row", even with class="row d-flex flex-wrap align-items-center align-items-stretch applied, it does ...

Were you intending to import the file firebase/app/dist/index.cjs.js?

Encountering the following error message: Error: Directory import 'C:\Users\My Name\Documents\Code\WebProjects\nextfire-app\node_modules\firebase\app' is not supported when resolving ES modules import ...

Seamless transition of text positioning and opacity as you scroll

After exploring multiple techniques for changing opacity and position on scroll, I am still struggling to connect them effectively. What I'm Looking For: I have a container with 4 words in a row. Only one word should be visible at a time, transition ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...