FeifanZ
FeifanZ

Reputation: 16316

Animate div position when other content size changes

I have a content div, and another div that goes underneath the first. The first div's content changes dynamically, and its height changes as necessary. Normally, the second div's position automatically gets bumped up and down as the height of the first div changes. How can I animate the movement of the second div, preferably using just CSS and JS (no jQuery)?

Here's a visual: enter image description here

On the left are my two divs, initially. Sometimes, div1 will expand in height to fit its contents, and div2 is pushed down. How can I animate the movement of div2?

Upvotes: 1

Views: 1516

Answers (2)

Stanley Stuart
Stanley Stuart

Reputation: 1145

Demo: http://jsfiddle.net/xS3y7/

#div1 {
    width: 50px; // Parent div needs width and height for this to work.
    height: 50px;
    background-color : red;
    position: relative;
}

#div2 {
    position: absolute;  //positioning based on parent.
    width: 100%; // 100% width of parent
    height: 20%; // 20% width of parent
    background-color: blue;
    bottom: 0px; // Place on the bottom
}​

The important thing to note is that the parent <div> must have either absolute or relative positioning, and the child <div> must have absolute positioning. Absolute positioning bases its positioning off its nearest parent element (in this case, #div1). Absolute positioning gives us the ability to place our element anywhere we want (in relation to the parent element), calculate values off, so this is really powerful.

For a good read up, check out Chris Coyier on CSS-Tricks.

Upvotes: 1

Luca Filosofi
Luca Filosofi

Reputation: 31173

function init() {
    var header = document.getElementById('header');
    var header_height = header.offsetHeight;
    header.style.height = '10px';
    header.style.overflow = 'hidden';
    var i = 0;
    var animation = setInterval(function () {
        if (i <= header_height) {
            header.style.height = (10 + i) + 'px';
        } else {
            clearInterval(animation);
            header.style.overflow = 'block';
        }
        i++;
    }, 10); 
}

ok, maybe some note are required? what you have to move is not the "second" div, but the "first", that by moving will automatically push the second at the bottom ( or end of the first ) hope this help

Upvotes: 2

Related Questions