Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically aligning my div within the body

Is there a CSS way to vertically align my div within the body element?

The thing is my div will have a different height each time, so its not constant.

These are the things I've tried but they dont work:

body { vertical-align: middle; }

#mainContent { 
   vertical-align: middle;
}

// Also this
body { margin-top: 20%; margin-bottom: 20%; }
like image 959
sazr Avatar asked Nov 28 '22 18:11

sazr


2 Answers

I did it without table: (demo on dabblet.com)

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, for an absolutely positioned element acts the same distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

This trick will work with any sizes of div.

HTML:

<div></div>

CSS:

div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    
    margin: auto;
}
like image 89
Vladimir Starkov Avatar answered Dec 05 '22 03:12

Vladimir Starkov


A common problem indeed. I have seen many people offering straight css solutions for this but they all require knowing the height of the element needing to be centered, so no help there.

I usually do it this way using jquery:

$(document).ready(function(){
    site.resize();

    $(window).resize(function(){
        site.resize();
    });
});

var site = {
    resize: function(){
        var new_margin = Math.ceil(($(window).height() - $('#mainContent').height()) / 2);
        $('#mainContent').css('margin-top', new_margin + 'px');
    }
};
like image 38
Kai Qing Avatar answered Dec 05 '22 03:12

Kai Qing