Search code examples
jqueryhtmlcsslayoutexpandable

Relatively Positioned expanding div's content not pushing down siblings


Sorry for the confusing title!

I have a list of expandable divs that, when clicked, show a child div, with content inside of it. The issue I'm having, however, is that despite the parent and child divs all being positioned relatively, expanding one div in the list does not push down the rest of the divs beneath it in the list. The expanded content just shows up behind the rest of the expandables.

Simple example here: http://jsfiddle.net/LT8h2/1/

<div id="cont1">This is an expanding div, click me!
    <div id="middle1">
        This is the content that should appear!
        <div>Inner 1</div>
        <div>Inner 2</div>
    </div>
</div>
<div id="cont2"></div>

In this example, the divs with IDs "cont1" and "cont2" are the expandables in the list. For simplicity, I have only given content to "cont1."

"middle1" represents the "expanded" panel, a div that will take up space to hold the content. Then the divs with text "inner 1" and "inner 2" are content that will be shown within the expanded panel.

The CSS is:

#cont1, #cont2 {
    position: relative;
    width: 746px;
    height: 50px;
    margin-bottom: 5px;
    text-align: left;
    background-color: #f2f2f2;
}
#middle1 {
    display: none;
    position: relative;
    height:45px;
    border: 1px solid red;
    width: 724px;
    padding: 17px;
    top:50px;
}

And finally the jQuery to expand the item on clicking:

$("#cont1").on("click",function() {
    var showing = ($("#middle1").css("display") == "block");

    if (showing) {
        $("#middle1").css("display","none");   
    }
    else {
        $("#middle1").css("display","block");   
    }
})

Solution

  • Set your height to min-height in "#cont1, #cont2". That will let the Div push down its buddy. If you change top:50px to margin-top:50px in #middle1 the display will fit in nicely instead of flowing out of the box.

    Additionally you can switch the .css() to slideUp() and slideDown() for a nice effect. Jsut throwing that out there if you are newer to jQuery.