Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts.

I attempted adding transition: height 0.2s ease to the div, but it didn't work as expected. How can I achieve height animation? CSS is preferred, but if necessary, I'm willing to use JavaScript.

JSFiddle Link

.tabGroup {
  background-color: brown;
  color: yellowgreen;
  transition: height 0.2s ease;
}
.tabGroup > div {
  display: none;
}
.tab1:checked ~ .tab1,
.tab2:checked ~ .tab2,
.tab3:checked ~ .tab3 {
  display: block;
}
<div class="tabGroup">
  <input type="radio" name="tabGroup1" id="rad1" class="tab1" checked="checked" />
  <label for="rad1">Tab 1</label>

  <input type="radio" name="tabGroup1" id="rad2" class="tab2" />
  <label for="rad2">Tab 2</label>

  <input type="radio" name="tabGroup1" id="rad3" class="tab3" />
  <label for="rad3">Tab 3</label>

  <div class="tab1">
    Content for Tab 1
  </div>
  <div class="tab2">
    Content for Tab 2
  </div>
  <div class="tab3">
    Content for Tab 3
  </div>
</div>

Answer №1

Instead of using max-height as suggested in many answers, I have found that setting it at a value higher than any possible content height allows for smooth transitions for divs with varying heights.

In this code snippet, the key is to ensure the max-height value is set above the highest possible height of any content within the divs. By doing so, all div heights can smoothly transition to accommodate their unique content heights. The implementation may not be perfect, but it effectively achieves the desired outcome.

.tabGroup > div {
    max-height:0px;
    transition:max-height 0.5s;
    overflow:hidden;
}

.tab1:checked ~ .tab1,
.tab2:checked ~ .tab2,
.tab3:checked ~ .tab3 {
    max-height:500px;
}

http://jsfiddle.net/guanzo/hgr0cd0q/4/

Answer №2

Building upon @EricGuan's response. An effective approach is to set the elements with absolute positioning and trigger the transition only when a specific choice is made.

For a demonstration, refer to this solution: http://jsfiddle.net/9m526ezL/2/

.tabGroup {
  background-color: brown;
  color: yellowgreen;
  position: relative; // make sure the container has relative positioning
}

.tabGroup > div {
  // each tab should have absolute positioning with a colored background.
  position: absolute;
  background-color: brown;
  color: yellowgreen;
  width: 100%;
  max-height: 0;
  overflow: hidden;
}

// As a recommendation, utilize IDs for your menu items instead of classes,
// since they should be unique in any case.
#rad1:checked ~ .tab1,
#rad2:checked ~ .tab2,
#rad3:checked ~ .tab3 {
  transition: max-height 0.5s;
  max-height: 600px;
}

UPDATE: There is an alternative version available here: http://jsfiddle.net/9m526ezL/4/

To create the illusion that the previous text disappears, a simple trick is to set the color to transparent or match the background color when the tab is inactive.

Answer №3

Although you may prefer to avoid using js, I believe that leveraging jQuery could simplify achieving the desired outcome.

Consider implementing a script such as the following:

$(document).ready(function(){
    $("#rad1").click(function(){
        $("#tab1").slideDown("slow");
    });
});

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

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

Issues arise with controlling access due to cache-control and canvas properties

I am attempting to utilize the browser canvas feature to manipulate images that are hosted on cloudfront. My goal is to configure cloudfront in a way that allows the browser to cache images with cache control set to max-age, while still enabling canvas edi ...

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

Exclude previous dates from the front end of ACF date picker

I am using Advanced Custom Fields to post job ads, and I have incorporated a date picker field for the end date of each job ad. <?php if (have_rows('jobs', 'option')): ?> <?php $now = time(); ?> <div i ...

Display a loading image as a placeholder while the Block is loading on the Viewport

Despite my extensive search for a solution to my problem, I have been unable to find one that addresses it directly. I am trying to display a "loading" image for 4 seconds before the content of the div is loaded. Unfortunately, I haven't been able to ...

Working with the collapse event in Bootstrap

After purchasing a template from ThemeForest, I found it to be absolutely amazing. However, I am struggling with using Bootstrap as it seems quite complex. The left menu is structured with collapsible ul and multiple li elements. I am seeking assistance o ...

Having trouble accessing JSON file again: "Encountered unexpected end of input error"

I have set up a cron-based scheduler to periodically retrieve JSON data from an external API every 2 minutes. The process involves writing the data to a file, reading it, cleaning it, and then storing it in a MongoDB collection. Everything works smoothly o ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

What are the steps to rename a file in Parcel without using automated tools?

Whenever I attempt to execute npm start or npm build, an error occurs stating that unknown: Entry /mnt/c/Users/kabre/Desktop/18-forkify/index.html does not exist. I was informed that Parcel could be renaming my index.html automatically. It's a bit con ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Which codec strings are considered valid for the web codecs API?

I am searching for a definitive list of valid strings that can be passed as the `codec` parameter in `VideoEncoder.isConfigSupported({ codec, width, height })`, but I have been unable to find a clear answer so far: The TS declaration file states that it m ...

How can a CSS class be inherited from a different file?

I have defined a class for styling a button: .client-header button { /*Properties*/ } And I also have a class to indicate when the menu is open: .client-menu-open { /*Properties*/ } My goal is to change the background of the button depending on ...

Utilize a Java application to log in to a website automatically without the need to click on

Opening two websites in my application is a requirement. Both of these websites have login forms with the action set to POST method. My goal is to automatically redirect to the next page after logging into these websites when I access them through my proj ...

Using jQuery to smoothly animate scrolling to the top of a

How can I create a "scroll to top" button at the bottom of my page that smoothly scrolls to the top? Despite using an "animate({scrollTop})" script, the scroll animation is not working and it jumps directly to the top. This is the script I am using: $(&a ...

The file-loader is able to organize images into separate folders when saving them. For example, an image file named "example.jpg" located in Project/Module

Hey there! I'm currently in the process of setting up a Webpack configuration that will generate files for each folder within my project. Unfortunately, creating a separate webpack.config file for each folder is not an option. So far, I have successf ...

Conceal/reveal div with initial partial visibility

http://jsfiddle.net/7RDBk/1/ At the moment, I am using slideUp and slideDown functions to hide and display a div. My goal is to have 25px of the div showing initially before expanding and going back to 25px when clicked. It seems like a simple task, but I ...

Error: Unable to access property 'addEventListener' of null. This issue appears to be related to a Chrome extension

It's been frustrating dealing with this persistent error. I'm in the process of creating my very first chrome extension and for some reason, I just can't seem to pinpoint what's wrong with this particular code snippet: let beginButton = ...