css: positioning images with overlap in a responsive layout

Two divs have been created with background images, both displaying the same image but in different colors - one grey and the other green. These images are waveforms.

Initially, only the grey image (div1) is visible while the green image (div2) remains hidden with its width set to 0. At a certain point on the page, a progress event occurs where the width of div2 needs to increase using Javascript based on the progress made, eventually covering div1.

The desired outcome is for X% of the space to display the green image depending on the progress, while the rest displays the grey image. To achieve this, both divs must be positioned at the same location and have the same size.

Here is an example of what the final result should resemble:

The attempted implementation looks like the following:

HTML:

<div class="left" id="container">
                    <div class="image original" style="background-image: url(/PATH/TO/IMAGE)">
                    </div>
                    <div class="image green" style="background-image: url(/PATH/TO/IMAGE_GREEN)">
                    </div>
</div>

CSS:

.image {
    position: absolute;
    top: 0;
    height: 100%;
    width: 100%;
    background-repeat: no-repeat;
}



   #container{
        position: relative;

      .original {
         width: 100%;
        }

       .green, .blue{
          width: 0%;
       }
    }

To ensure the entire background image is contained within the div container, it was necessary to add:

background-size: 100% auto

Including this caused the image to become responsive. However, when increasing the width of div2 from 0 to 100%, the background image did not align perfectly with that of div1 during the process as the whole image was compressed into the smaller div2. As a result, it appeared as shown here:

The main objective is for the two background images to match seamlessly throughout the transition.

How can this particular effect be successfully achieved?

Answer №1

If you're looking to design a progress bar that mimics a background image filled in horizontally based on the progress percentage, consider using just one div instead of two. You can achieve this effect by incorporating a transparent gradient along with the background image and animating it accordingly.

Here's an example:

<div class="progress"></div>

In your CSS:

.progress {
  width:800px;
  height:150px;
  border:10px solid #555;
  background-image:
    linear-gradient( 
      to right,
      rgba(0, 255, 0, 0.45), 
      rgba(0, 255, 0, 0.45) 50%,
      rgba(0,0,0,0) 50%,
      rgba(0,0,0,0)
    ),
    url('https://placeimg.com/800/150/animals/grayscale');      
}

To update the gradient transparency dynamically using JavaScript, you can modify the background-image property with new values as needed.

Check out a complete demo with JS implementation here: http://codepen.io/zesposi/pen/apyNGq

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

Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes: <div class="token-checkboxes"> <span class="checkbox-span" v-for=" ...

The script ceases to function once the page is loaded from a JSON file

I'm facing an issue on my shopping website where the items and products are loaded from a JSON file. The problem is that once the page has loaded, the script fails to work properly. If the items take a little longer to load on the page, the script doe ...

Exploring the OAuth 2.0 integration with OpenID Connect, Loopback, and Keycloak

I'm having trouble establishing a connection to Keycloak from Loopback. I've been experimenting with the keycloak-connect library available at: https://github.com/keycloak/keycloak-nodejs-connect This snippet shows my current implementation in ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

The scrollable dialogue disrupts the background's ability to flex and grow

My page layout is pretty simple: <main> <header>Header</header> <section>Content</section> <footer>Footer</footer> </main> <dialog>Dialog</dialog> In terms of CSS, here's how it ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Error: The call stack has reached the maximum size limit in nodejs and reactjs

When I attempt to submit the token received from my registration using the code snippet below, I encounter an error stating "maximum call stack exceeded." exports.activationController = (req, res) => { const { token } = req.body; exports.activation ...

Looking for a solution to align the header properly in your React app?

Struggling with aligning a header? The CSS property of the header is inherited from the app's CSS file. For example, in the image below, "Our Mission" is the header that needs to be left-aligned. Looking for some assistance here. You can find the app. ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

When encountering an "uncaught SyntaxError" in the $.parseJSON function, one may want to investigate

When using this jQuery function, I encounter an Uncaught SyntaxError: Unexpected token u error if the cookie $.cookie('chk_ar') is undefined. function checkBgNoise() { // checks background noise option state, // activates 'on' click i ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Having trouble retrieving the accurate height value for the UIWebView

Currently, I am attempting to retrieve the value of a UIWebView using the following approach: var webview = self.articleContent println(webview.frame.size.height) // This outputs 300 // Now rendering the w ...

Number each element in sequence

Looking to give sequential numbering to elements by iterating through them. For instance, if there are 6 input elements, the goal is to update their names correspondingly like "name=input1", "name=input2", and so on. This involves using a for loop to reas ...

Transferring values from jQuery AJAX to Node.js

Is there a way to successfully pass a variable from jQuery to nodejs without getting the [object Object] response? I want to ensure that nodejs can return a string variable instead. $('.test').click(function(){ var tsId = "Hello World"; ...

Creating a JavaScript class definition without the need for instantiation

I am looking to create an empty data class in JavaScript that can later be filled with JSON data. In C#, I would typically do something like this: class Person { string name; int age; Person[] children; var whatever; } However, when I try ...

Tips for storing data from a table using a button

I have implemented a data table to display information from a database. I am looking for a way to save user information whenever they export data in Excel, CSV, or PDF format from the table. I have already created a function to handle saving user data, but ...

Searching for the class _XWk using BeautifulSoup: A beginner's guide

I have discovered a way to locate Google's "quick answer box" by searching for the "_XWk HTML Element using the code below: from bs4 import BeautifulSoup # Beautiful Soup is part of the bs4 package import requests URL = 'https://www.google.com/ ...

Determine whether the child element extends beyond the boundaries of the parent element

I am currently working on determining whether a child element is visible within its parent element. To achieve this, I am comparing the width of the parent element to the position of the child element using position().left. Given that I have multiple dist ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...