I have a container within my body and I need to set this element to centered vertical alignment. I need to do this also dependent on body height, and change it dynamically.
I tried with something like the below code, but it doesn't work perfectly and most importantly not dynamic. Note: I can't do this with css.
var ah = $('body').height();
var ph = $('#main_container').parent().height();
var mh = Math.ceil((ph-ah) / 2);
$('#main_container').css('margin-top', mh);
I have a container within my body and I need to set this element to centered vertical alignment. I need to do this also dependent on body height, and change it dynamically.
I tried with something like the below code, but it doesn't work perfectly and most importantly not dynamic. Note: I can't do this with css.
var ah = $('body').height();
var ph = $('#main_container').parent().height();
var mh = Math.ceil((ph-ah) / 2);
$('#main_container').css('margin-top', mh);
Share
Improve this question
edited Aug 28, 2012 at 20:43
spolto
4,5514 gold badges28 silver badges34 bronze badges
asked Aug 28, 2012 at 20:34
LukasLukas
7,75420 gold badges79 silver badges127 bronze badges
2 Answers
Reset to default 2Bind it to the resize
event:
$(window).on('resize', function() {
var $container = $('#main_container');
var height = Math.ceil(($container.parent().height() - $('body').height()) / 2);
$container.css({marginTop: height});
}).trigger('resize');
It won't be as smooth as CSS, but it will work. Why can't you do it with CSS?
You can inject CSS using JQuery:
$('#main_container').css("position", "absolute");
$('#main_container').css("margin-top", "auto");
$('#main_container').css("margin-bottom", "auto");
$('#main_container').css("top", 0);
$('#main_container').css("bottom", 0);
If you also want to horizontally center it, you can delete the margin-top
and margin-bottom
lines, and add:
$('#main_container').css("margin", "auto");
$('#main_container').css("left", 0);
$('#main_container').css("right", 0);