the_
the_

Reputation: 1173

CSS Vertical Center with dynamic divs

I have a div called container that I'm trying to vertically center. I've got it vertically centered, but now I'm adding divs to it via jQuery, like:

$("#add").on("click", function () {
    $(".elements").append("<div class='element'>World</div>");
});

Here is a JSFiddle: http://jsfiddle.net/CDk4E/

What the problem is:

If you haven't added any divs yet, the page looks good (it's vertically centered). But if you start adding div's, the .element div that contains "Hello" gets pushed to the top. But what I'd really like to do is instead have it be kept in it's original spot, and have the other .element divs be just added on to the bottom.

EDIT: Also, the first element is always a fixed size.

Upvotes: 0

Views: 78

Answers (1)

marcineck
marcineck

Reputation: 281

Try to add padding:50%; to your .container

<style>
    html, body {
    height: 100%;
}
.wrapper {
    height: 100%;
    width: 500px;
    margin:0 auto;
    display: table;
}
.container {
    display: table-cell;
    height: 100%;
    padding-top:50%;
    border:1px red dashed;
    position:relative;
}

.element{
    background:purple;
    color:#FFF;
    width:100%;
    padding:10px;
}

</style>

Here is outcome: http://jsfiddle.net/CDk4E/2/

Upvotes: 3

Related Questions