最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 2

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?

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);
发布评论

评论列表(0)

  1. 暂无评论