我的身体里面有一个容器,我需要将此元素设置为居中的垂直对齐方式。我需要这样做也取决于身高,并动态改变它。
我尝试使用类似下面的代码,但它并不完美,最重要的是不是动态的。注意:我不能用css执行此操作。
var ah = $('body').height();
var ph = $('#main_container').parent().height();
var mh = Math.ceil((ph-ah) / 2);
$('#main_container').css('margin-top', mh);
答案 0 :(得分:2)
将其绑定到resize
事件:
$(window).on('resize', function() {
var $container = $('#main_container');
var height = Math.ceil(($container.parent().height() - $('body').height()) / 2);
$container.css({marginTop: height});
}).trigger('resize');
它不会像CSS一样流畅,但它会起作用。你为什么不能用CSS做到这一点?
答案 1 :(得分:1)
您可以使用JQuery注入CSS:
$('#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);
如果您还想要横向居中,可以删除margin-top
和margin-bottom
行,然后添加:
$('#main_container').css("margin", "auto");
$('#main_container').css("left", 0);
$('#main_container').css("right", 0);