What is the best way to swap overlapping elements using CSS transitions?

Imagine this scenario: I have four different elements overlapping within a parent element, structured like so:

<body class="one">
    <div id="overlapping">
        <div class="one">1</div>
        <div class="two">2</div>
        <div class="three">3</div>
        <div class="four">4</div>
    </div>
    ...

The CSS is set up in the following manner:

.one, .two, .three, .four { display: none; }
body.one .one,
body.two .two,
body.three .three,
body.four .four {
    display: block;
}

Afterwards, there's some javascript involved along with buttons to switch classes on the 'body' element.

This approach works effectively, but I want to introduce a CSS transition for smoother block switches. The issue is that these blocks vary in height and width, making it challenging to animate based on fixed dimensions without compromising responsiveness. Unfortunately, transitions cannot be applied directly on the display property.

Animating visibility or opacity is not feasible either because hidden or transparent elements still occupy space in the layout. This means true overlap can only be achieved when elements have a display property of none.

(One potential solution could involve positioning all elements at the top left of #overlapping using CSS rules to stack them neatly while allowing for normal text flow. However, such a method has yet to be discovered.)

So, the question remains - how can I animate these switches? Is there a pure CSS solution, or should JS animations be considered?

Answer №1

This unique approach has proven to be the most effective for me (with minimal syntax):

body {
  #overflow > div
    height: 0;
    opacity: 0;
  }

  &.one .one,
  &.two .two,
  &.three .three,
  &.four .four {
    height: 100%;
    opacity: 1;
  }
}

#overflow {
  overflow: hidden;
  div {
    transition: height .9s;
    transition: opacity .9s;
    overflow: hidden;
    display: block;
  }
}

This solution works well because all my internal divs are of a consistent (though varying) height. While I am open to a more general solution, it seems that such a solution remains elusive to many.

Answer №2

While CSS3 offers a few animation possibilities, some developers prefer using jQuery for more advanced effects.

To explore jQuery animations further, consider referencing the jQuery API documentation on .animate.

$(".one").animate({opacity: 0.4, display: "block"}, 1500);

$(".two").animate({opacity: 0.4, display: "none"}, 1500);

Experiment with different changes to see what works best for your project...

Adjusting the div's position to relative can also help with overlapping elements.

If you need any more assistance, feel free to let me know!

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

Utilizing the Bootstrap grid system to align two div elements in one row, with one centered on the page and the other positioned to

Looking for a solution to align two divs inside a flex container - the first centered horizontally and the second aligned to the right. Requirements: must use bootstrap only. |---------------------------------------------| center ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

Is there a way to move my (bootstrap) elements to the bottom of the columns without using position absolute?

I'm currently working on 3 columns with icons at the bottom, as seen on the bottom of this website: I'm trying to align the icons directly to the bottom of each grey box without relying on position absolute which is what I'm currently using ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

Getting the time difference relative to the current time using date-fns from a MySQL datetime - a step

I am trying to implement a relative time feature like ... ago in my react blog posts without relying on moment.js. The date of the post is stored in mysql using the datatime data type, for example 2023-02-01 21:25:33 This is what I have attempted in the c ...

Using Joi validation in Node.js to conditionally disallow certain keys

As a beginner in nodeJS, please bear with me if my question seems naive. I am trying to implement conditional payload based on another key. price: Joi.when('pricing', { is: 'VARIABLE', then: Joi.number() .min(1) ...

The function is failing to provide a return value

In the Game.js file, there is a function that I am working on Game.prototype.onClick = function(event){ var x = event.x; var y = event.y; if (this.blueDeck[0].contains(x, y)) alert("Blue Deck Clicked"); } The OnClick function is ca ...

Is it possible to implement the splice() method within a forEach loop in Vue for mutation

Hey there! I'm looking for a more efficient way to replace objects that match a specific index with my response data. Currently, I'm attempting to use the splice() method within a forEach() loop in Vue.js. However, it seems to only remove the obj ...

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

When my route in NextJS processes the request, it returns a ReadableStream from req

I am encountering an issue with my code and I have tried looking for solutions in other similar questions without any success. Is there anyone who can assist me? Here is the content of my route.js file: import dbConnect from "@/lib/dbConnect"; i ...

Invalid template detected within the Kendo dropdown component

I am trying to create a template that will only be displayed if the data value is "Low". This is how I have set up my template column: template: '# if( data=="Low" ){#<span><i class="fa fa-square blue"></i> <span># } ' U ...

Which is better for narrowing object property types: using dot notation or object literal notation?

Is there a reason why type narrowing by assignment behaves differently based on whether we use dot notation or object literal notation? Below are two examples to illustrate this discrepancy. type MyObj = { x?: number | string } let obj1: MyObj = {} obj1.x ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...

Exploring the wonders of looping through arrays with JavaScript and jQuery

I am having trouble getting this function to work properly. My goal is to replace certain characters when a key is pressed. The code works fine using the variable `replace_list` instead of `replace_list["russian"]`, but I actually need different "replace ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Can JavaScript be used to continuously monitor a window variable object in real-time?

Is there a way to dynamically control a variable in JavaScript? I'm currently working on a code that needs to display a button when it reaches the last signature of an automatic request process. The code for activating/deactivating the button is show ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

JavaScript is claiming that my class method is invalid, despite the fact that it is obviously a valid function

Implementing a genetic algorithm using node has been my latest challenge. After browsing through the existing questions on this topic, I couldn't find anything relevant to my issue. The problem arises when I attempt to call the determine_fitness metho ...

Having trouble with Axios PUT request not sending complete data to the server using JavaScript

One issue I'm encountering is that when sending an axios request with specific data, not all of the data gets updated in the user model. Here's a look at my code: Here is the Front-End code with axios request: import axios from "axios" ...