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:

https://i.sstatic.net/ojobZ.png

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:

https://i.sstatic.net/oSXLF.png

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

What is the best way to choose all text within a code box without highlighting the entire webpage?

I developed a CSS code specifically for my blogspot site to organize and store all of my code and technical snippets. .code { background:#dae6ef; background-repeat:no-repeat; border: solid #5C7B90; border-width: 1px 1px 1px 20px; color ...

Extracting data from a Wikipedia table using web scraping in JavaScript

I'm attempting to extract information from a specific website. <script> var convertToInt; var allData = []; $.ajax({ url: "http://en.wikipedia.org/wiki/Demographics_of_Europe", type: 'GET', cache: false, success: func ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Despite working smoothly with an HTML form tag, the "req.file" multer is undefined when it comes to HTTP requests from a script

I have created a basic file uploader using multer in Node.js, which works well when uploading files using an html form like this: <form id="uploadForm" enctype="multipart/form-data" method="post"> <input type="file" name="userFile" /> ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Troubleshooting: CSS border-radius issue with embedded iframe

I am struggling to embed an iframe from my Blogger site into a specific section on my website and round its corners using CSS. I followed a tutorial that suggested using overflow: hidden;, but for some reason, it's not working in my case - see the ima ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

Store in database and forward to a different web address

I have created an interactive quiz using jQuery. I need to add a specific feature at the end of the quiz. if (answered_questions === total_questions) { save the user's score to the database; redirect to specified URL; } The redirect_url is ...

Challenges arise when using Bootstrap 4 for country selection

There have been reports that bootstrap 4 country select is not functioning properly. In an effort to troubleshoot, I delved into the documentation to find a solution. To make bootstrap-select compatible with bootstrap 4, refer to: Bootstrap 4 beta-2 ...

Resolving Div Alignment Issues in Internet Explorer with jQuery CSS AddClass and RemoveClass

I've set up an HTML table with a hover highlight feature using jQuery and CSS. Here's how my hover event is structured: $('#' + element.id + ' tr:not(:first,[class="summary_row"])').die('mouseover mouseout').live(&a ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

Obtain the name of the object method from inside the method itself

Imagine having an object like this: var app = {} inside which there is a method: app = { initialize: function () { } } Is it possible to retrieve the name of the method 'initialize' from within the initialize() function without explicit ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

What is the best way to retrieve the value from a PHP request?

I am encountering an issue with a multiselect form field named properties[]. When I attempt to retrieve the values in my controller using dd($request->get('properties')), it gives me ["1,2"]. However, trying to access the first ele ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

Fetching data within a defined time range in Django

Currently working on creating my dashboard, the design is all set. However, I'm facing a challenge in retrieving specific data sums from my MySQL database. For instance, how can I retrieve the revenue of the last 15 days? models.py class JaGAnalytics ...