Smoothly animate the height change of dynamically inserted content within a DIV using CSS transitions

Here is the template I am currently working with:

<div class='content'>
    {{content}}
</div>

Along with the following style:

.content {
  margin-top: 30px;
  background-color: skyblue;
  width: 300px;
  transition: all linear 0.5s;
}

I am facing an issue where the {{content}} dynamically grows or shrinks, but the CSS transition does not work properly when new content is injected into the element. How can I ensure that the transition works correctly even when more content is added?

You can view the code on this Plunker link.

Thank you,

Amit.

Answer №1

It is important to note that transitions in CSS only apply to changes made directly to the CSS properties, not for changes calculated by the browser.

A technique you can use is to nest a div, apply overflow: hidden to the outer div, then set the computed height of the inner div as the height of the outer one to achieve a smooth transition effect.

CSS:

#outer {
    margin-top: 30px;
    background-color: skyblue;
    width: 300px;
    transition: all linear 0.5s;
    overflow: hidden;
}

HTML:

<button id="more" onclick="increase();">More</button>
<button id="more" onclick="decrease();">Less</button>
<div id="outer">
    <div id="inner">
        lorem ipsum
    </div>
</div>

JS:

function increase()
{
    var o = document.getElementById('inner');
    var t = o.innerHTML;
    for (var i=0 ; i<20;i++)
        t += " lorem ipsum";
    o.innerHTML = t;
    adjustHeight();
}

function decrease()
{
    var o = document.getElementById('inner');
    o.innerHTML = "lorem ipsum";
    adjustHeight();
}

function adjustHeight()
{
    var i = document.getElementById('inner');
    var o = document.getElementById('outer');

    o.style.height = window.getComputedStyle(i).height;
}

Check out the working fiddle: http://jsfiddle.net/Lnts7w1f/

Answer №2

Thanks to the guidance of @jcaron's response, I successfully implemented a sorting feature in a react component. Whenever the 'activeSubsection' button is clicked, the useEffect hook is triggered.

    const [sectionsHeight, setSectionsHeight] = React.useState("0px")
    const sectionsDiv = React.useRef();

    React.useEffect(() => {
        
        setSectionsHeight(sectionsDiv?.current?.offsetHeight + "px")
    
    }, [activeSubsection])

    {!hideSections && 
        <div style={{ overflow: "hidden", height: sectionsHeight, transition: "0.2s" }}>
          <Sections ref={sectionsDiv} className="largeScreen">
            {!!subsectionSections && subsectionSections.sort((a, b) => a.node.slug.localeCompare(b.node.slug)).map((section, index) =>
              <Link key={index} href={'/'+slug+'/'+section.node.slug} scroll={false}>
                <Section
                  active={activeSection == section.node.slug} transition={true} bold={activeSection == section.node.slug}
                >
                  {section.node.title}
                </Section>
              </Link>
            )}
          </Sections>
        </div>
    }

This snippet doesn't cover the entire component, but it should provide a good overview.

Answer №3

Here's a little trick you can use in this situation. It may or may not meet your specific requirements.

The magic of css transition effects lies in its ability to animate changes in css properties that have both previous and changed values. In the case of altering the height of a div content, the actual css property height remains unchanged, hence no animation effect is observed.

To work around this limitation, you can calculate the inner height of the div and dynamically set it as its own height, triggering the desired animation. I've devised a function for this purpose, along with a span element to control the inner dimensions of the div.

Simply invoke the function whenever there is a change:

<div class='content'>
  <span id="height-control">
    {{ctrl.content}}
  </span>
</div>

Function in JavaScript:

var spn = document.getElementById("height-control");
var UpdateHeight = function () {
    var h = spn.offsetHeight;
    spn.parentNode.style.height = h + "px";
};

http://plnkr.co/edit/p6QRAR5j4C8d0d0XRJRp?p=preview

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

Hitting the enter key to choose a value from a dropdown menu will automatically submit the form

I've encountered an issue while using ui-select. Whenever I press enter to select searched results, the selection is made and the form automatically submits. I'm having trouble figuring out what the problem is. Here is the HTML code snippet I am ...

The MUI Modal is too large for the display

I'm using a Modal component from MUI in my project and I am facing an issue with displaying a large JSON object inside the modal. The problem is, the top of the modal extends beyond the screen height and even after making it scrollable, I am unable t ...

Reveal Password Feature in Angular After User Click

I am working on an inventory page that includes a password field. My goal is to initially hide the password and display it as points (****) instead. I would like the password to be revealed either when clicked or through a pop-up. JS var retrieveCert ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...

The browser is displaying the scene, but the Three.js Geometry is not visible

After following a tutorial and successfully getting the entire scene to work within the body tag, I decided to move it inside a div. However, now only the scene itself is rendered. Despite not receiving any errors and ensuring everything is accessible thro ...

Flex box causing Bootstrap5 responsive table to overflow

Need help with fixing overflow issue in a fixed-width div used as a left sidebar. The main content renders correctly except for tables with many columns, causing overflow before the scroll bar appears. How can this be resolved? Various layout attempts hav ...

Performance Issues Arise with Rapid Clicking [jQuery]

Having trouble with a gallery script I created that includes thumbnails, a large image, and navigation arrows. When you rapidly click on thumbnails or arrows during the transition, it causes delays in the process. The more clicks you make, the more noticea ...

Creating a responsive web design with a user-friendly CSS grid layout

Currently, I am delving into the realm of CSS grid to better comprehend its functionality. In my layout design, there are two menus (colored in red) positioned on either side of a central main content box (colored in blue). As the screen size reduces and ...

Hovering over the Laravel Breeze dropdown will activate a dropdown feature

Recently, I've been working on a project with Laravel Breeze and have been utilizing some default components. The dropdown component used in the navigation bar caught my attention. By default, it requires a click for the menu to drop down below. Howev ...

"Embracing Angular2 RC6 with angular-cli: A guide to smoothly upgrading your projects' Angular2 version

After installing angular-cli on a fresh machine, I ran ng --version and received the following: angular-cli: 1.0.0-beta.10 node: 6.5.0 os: win32 x64 It appears to be the latest version according to https://www.npmjs.com/package/angular-cli. When creati ...

Sending simple form information through AJAX to a PHP web service

Attempting to send form data via jQuery and Ajax to a PHP web service (php file) for echoing the results. This is my index.html file <html> <head> <title>PHP web service &amp; AJAX</title> <link rel="stylesheet" type="text/ ...

Position three paragraphs in the center of a div container

Is there a way to center 3 paragraphs in a div? I have separate divs for each paragraph and one main div that holds all three nested divs. div.first { font-family: 'Kanit', sans-serif; color: aliceblue; width: 30%; float: left; ...

Could somebody please clarify the purpose of Bootstrap's `_root.scss` file?

After reading through the Bootstrap introduction [1], I added the following code snippet to my .html file: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384- ...

Learn the process of generating sequential heading numbers for topic headings in each HTML document using DTA or XHTML

I attempted to include hierarchical numbers for topic headings in dita2xhtml_eclipsehelp.xsl. (DITA OT HTML output) However, I am facing difficulty in producing numbers similar to the following in each html file: 1 heading text 1.1 heading text 1.1.1 Head ...

Executing a callback function in AngularJS after dynamically rendering elements with `ng-repeat`

Many posts demonstrate how to implement callback functions in directives to wait for ng-repeat to finish before calling a function. Here is an example: <div ng-repeat="Object in Objects" class="objectClass" on-finish-render>{{Object.Overlay}</div ...

Raphael JS Path Animation: Wiping Away

I have successfully created a line animation using RaphaelJS, which can be viewed on this jsfiddle link - http://jsfiddle.net/7n040zdu/. My next challenge is to create an erasing animation that follows the initial one. This erasing animation should mimic t ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

How to Display Full Lightbox Image on both Tall and Short Height Browsers

Hey there! I'm showcasing my portfolio using lightbox, but I've run into a little issue. When the browser height is full, everything looks great - you can see the entire image, along with the paragraph and buttons. https://i.stack.imgur.com/UCJG ...

unable to load the ajax file

While setting up Ajax, I encountered an error message in IE that reads: Description: An issue occurred during the processing of a configuration file needed to handle this request. Please check the specific error details below and adjust your configuration ...

Issue with CSS3 animations

.button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; ...