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

Conceal content within a bullet point

I'm encountering an issue with this specific element. HTML <div class="navbar slide-menu"> <div class="container"> <ul class="nav navbar-default"> <li class="brand"><a href="#">Menu</a></li> ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

The then() function in Node.js is triggered before the promise is fully resolved

I'm struggling to get my Promise function working as intended. Here's what I need to accomplish: I am receiving file names from stdout, splitting them into lines, and then copying them. Once the copy operation is complete, I want to initiate oth ...

Ways to retrieve Data obtained in response using superagent

I am currently working on hitting an API and extracting the data received in response. To achieve this, I am utilizing superagent to retrieve the data from the API. I have inspected my network tab, however, I am encountering an issue where I want to extra ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

What is the best way to eliminate a specific character from the key of an array of objects using JavaScript?

My JavaScript object looks like this: result = [ {"Account_ID__r.Name":"Yahoo Inc Taiwan","Contact_ID__r.Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42283427302c2d2e2602362a27313 ...

Looking for assistance with a CSS selector in jQuery

I am working with a WordPress blog that has multiple pages with dropdown subpages on hover. However, I only want the main pages to have links, not the subpages. To achieve this, I am using some basic JavaScript. jQuery(document).ready(function(){ jQ ...

What are some ways to customize the appearance of my ReactJS application while it's being viewed on Chrome on

I'm currently in the process of running my ReactJS app on a Panasonic Vierra Smart TV browser. After importing core-js and babel-polyfill, I managed to load the webpage but encountered an issue with the UI alignment. The styling does not display corre ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

A quirky bug with Tumblr's JS/Jquery Infinite Scroll and Masonry feature

As someone new to JS/JQuery and masonry, I seem to be facing a puzzling issue with overlapping posts/divs. Despite my extensive search for answers, I have run out of ideas. The problem arises from the content at this link: Below is the complete theme cod ...

Uploading files and data in Laravel using Vue.js and Vuetify: A step-by-step guide

My Vuetify form is working fine with text input, but when I try to include images, I encounter the error GET http://danza.test/thumbnails[object%20File] 404 (Not Found). How can I successfully pass both text and images in a form? This is part of the code ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...

What is the reason that when the allowfullscreen attribute of an iframe is set, it doesn't appear to be retained?

Within my code, I am configuring the allowfullscreen attribute for an iframe enclosed in SkyLight, which is a npm module designed for modal views in react.js <SkyLight dialogStyles={myBigGreenDialog} hideOnOverlayClicked ref="simpleDialog"> <if ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...