Struggling to stack HTML elements with z-index while implementing a scroll effect

I need help with positioning four HTML elements on my page. One of them has a scroll effect and scrolls downward. I want the green-colored div to always be above Block B but below Block C. When Block B overlaps with Block C, I would like Block C to be hidden behind Block B. Also, I want the darker green element to display in the same way as Block A.

For reference, you can view the corrected Codesandbox here.

return (
      <div className=" h-[200vh] w-full flex flex-col items-center">

        <div className=" relative mt-[300px] bg-green-900 w-full h-[200px] text-black text-center flex flex-col justify-between text-white ">
          <div className=" relative z-10">
            Block A
          </div>
        </div>

        <Image
          src={borderSvgTexture}
          className=" relative  h-auto  w-full min-w-screen  mt-[-5px]   "
          alt=""
        />

        <div className=" bg-blue-600 w-full h-[200px] mt-[-50px]  ">
            <div className=' mt-[100px] text-center'>Block B</div>
        </div>

      <motion.div
        style={{ y }}
        className="h-[500px] flex justify-center absolute inset-x-0 mx-auto max-w-[1800px] text-white"
        >
        <div className=" w-[100px] h-[100px] bg-red-500">Block C</div>
      </motion.div>
    </div>
  )

I've experimented with different z-index combinations, but I can't seem to achieve the desired layout without some unintended hiding occurring. I'm starting to wonder if what I envision is even possible.

Answer №1

After extensive work, I have devised a solution to accurately determine component scroll positions and dimensions in react by utilizing the Element:getBoundingClientRect() method.

The approach involves leveraging useRef hooks to access component properties, specifically the top and bottom values for the respective divs. This allows us to establish criteria for when the height, z-index, or visibility of Block C should be adjusted.

An additional update has been made to incorporate seamless integration with image patterns within this implementation.

For a practical demonstration, refer to the CodeSandbox, where my version of the code showcases the proposed method. Please note that occasionally, Block C may not be visible upon initial loading in the sandbox. Simply refresh the page to ensure accurate capturing of the initialHeight for Block C.

The pivotal function, listenToScroll, is invoked through useEffect whenever the user engages in scrolling activities as part of the scrollHandler.

This function effectively establishes three distinct scenarios relating to Block C, consequently influencing its height and z-index attributes.

const listenToScroll = () => {
  if (cRef.current && bRef.current) {
    const cRect = cRef.current.getBoundingClientRect();
    const bRect = bRef.current.getBoundingClientRect();
    
    const cBottom = cRect.bottom;
    const cTop = cRect.top;
    const bTop = bRect.top + (bRect.height/5); // Considering image height
    let cHeight = cInitialHeight;

    if (cBottom > bTop && cTop < bTop){
        cHeight = cRect.height - (cBottom - bTop);
        cHeight = cHeight < 0 ? 0 : cHeight;
        cHeight = cHeight + "px";
        setCStyle({...cStyle, height: cHeight})
        setCIndex("z-30");
    }
    else if (cBottom < bTop && cRect.height < cInitialHeight){
        cHeight = cRect.height + (bTop - cBottom);
        cHeight = cHeight > cInitialHeight ? cInitialHeight : cHeight;
        cHeight = cHeight + "px";
        setCStyle({...cStyle, height: cHeight})
        setCIndex("z-30");
      }
    else if(cTop > bTop){
      cHeight = cInitialHeight;
      setCStyle({...cStyle, height: cHeight});
      setCIndex("z-0");
    }
  }
};

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

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

Give the inner container the ability to expand to fill the remaining space

After formatting my HTML code as shown below: https://i.sstatic.net/oaVVg.png The blue rectangle takes up 70% of the outer container's width, while the green rectangle occupies the remaining 30%. My goal is to have the blue rectangle expand to fill ...

Module node - found to be incompatible as it is not supported in the create react app environment

Encountering an issue while attempting to install react / babel on my computer, seeking assistance from anyone who can provide guidance. Running Ubuntu 20.04 LTS with node -v 14.4.0 and npm -v 6.14.5, so following the documentation should be fine. The pr ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

Increased Z-index on an unfamiliar site

I'm in the process of enhancing the Moodle platform at my school with a userscript, and I want to create a sleek UI for it. One feature I want to add is a progress bar that stays fixed at the top of the browser viewport so that it remains visible as ...

Using node.js to modify the appearance of the form submission button's color

When using node.js to insert data from an HTML form into a database, validation typically occurs on the server side. I am wondering if there is a way to customize the CSS class associated with the submit data button in node.js. For example, I would like ...

"Removing the blue initial loader from Filestack during initialization: A step-by-step guide

Currently, I am facing an issue with a button that triggers the filestack uploader in my React application. The functionality works as expected, but I am struggling to override the default blue spinner/loader that is displayed with the filestack uploader. ...

What is the best way to showcase my subscription form on a web browser?

I am encountering an issue with my code. My goal is to generate a subscribe form modal. Although I have incorporated the subscribe form in my HTML document, upon running the code in the browser, the subscribe section is not visible. Can anyone offer assist ...

Guide for implementing pagination on a lengthy list with React MaterialUI

I'm currently working on a project using react and MaterialUI to create a list with filter functionality. The list will be populated with data from an Http request and may contain a large number of items. I was researching pagination in the MaterialUI ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Difficulty in aligning elements to the edges of the screen

How can I adjust the positioning of these two arrow indicators to be aligned with the left and right edges of the screen, regardless of size? .arrow-container { position: absolute; top: 37%; width: 95%; display: grid; grid-template-columns: 10 ...

What is the reason that applying bg-dark on a Bootstrap navbar prevents the background-color from being applied?

Is it possible to change the background-color of a Bootstrap navbar by adding custom CSS? I have my own CSS file loaded after Bootstrap, so I assumed my styles would take precedence. However, when I try to apply a new background color to the navbar, it doe ...

Styling the navigation menu for mobile devices

How can we transition from a menu like this : https://i.sstatic.net/qQ2k1.png to this when the screen size reaches a specific width: https://i.sstatic.net/AUM4v.png In essence, replacing certain texts with icons. Is pre-defining it and changing the dis ...

I am currently engaged in a Portfolio project, where my objective is to ensure that all images are optimized for responsiveness

While Bootstrap ensures that relative images are responsive, absolute images may not be. This can cause alignment issues when the browser window is resized on mobile devices. .title-img { position: relative; width: 100%; height: 100%; } .skill-b ...

Is there a way to reposition the arrows in this Bootstrap 5 accordion to appear ahead of the text?

Here's an example from Bootstrap 5 web page that I've been working with (https://getbootstrap.com/docs/5.0/components/accordion/). My query pertains to positioning the arrows before the text in the accordion items. Despite attempting various appr ...

Issue with modal not being able to close the embedded video iframe

I have created a demo of a video in my footer that uses external CSS files and works perfectly. However, when I added it to the project, everything works except for closing the video. After clicking the play button in the footer, a modal appears on the sc ...

Has React reached its full potential without the integration of Redux?

Is it possible to render a component to two separate routes with different authentication levels? One editable for authenticated users and the other read-only for unauthenticated users. Currently, all application state resides in React and is passed down ...

Is it possible to animate the change in background color dynamically using jQuery?

I am struggling to implement a change/animate feature for the background color. When I place the background script within the form submit event but outside the ajax call, I can briefly see the color change. However, once the remote content loads, the colo ...

Tips for filling the offset space with a column

Having a bit of trouble phrasing my question, but here's the issue I'm facing: Currently, I need to develop two different views, the first being the mobile view However, I'm experiencing some difficulties with the second view, which can be ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...