Lukas
Lukas

Reputation: 7734

How to dynamically change element margin-top dependent on body height

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);

Upvotes: 0

Views: 13740

Answers (2)

Ian
Ian

Reputation: 6134

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);

Upvotes: 1

Blender
Blender

Reputation: 298392

Bind 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?

Upvotes: 2

Related Questions