使用 jquery 在 div 中垂直对齐 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/965684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:16:25  来源:igfitidea点击:

vertical align div within a div using jquery?

jqueryhtmlcssvertical-alignment

提问by mark smith

Anyone have any experience with jquery vAligh plugins or similar?

任何人都对 jquery vAligh 插件或类似插件有任何经验?

I tried to align for the following but it fails.. I was using a simple valign plugin (I will put the plugin at the end, its a jquery extension), if anyone can help it would be really helpful...

我尝试对齐以下内容,但失败了..我正在使用一个简单的 valign 插件(我将把插件放在最后,它是一个 jquery 扩展),如果有人可以帮助它会非常有帮助......

var overlayLayer = $("<div id='office-location'></div>").addClass('modal-overlay');
$('body').append(overlayLayer);

$('<div id="content-for-overlay" style="background-color: white;"></div>').appendTo(overlayLayer);

this.render({ to: "content-for-overlay", partial: "office-location-modal" }); // this just copies html into the layer

$('#content-for-overlay').vAlign(); THIS USES a plugin called valign but it doesn't align

$("body").css("overflow", "hidden");
$('#office-location').css("opacity", 0.8).fadeIn(150);
$('#content-for-overlay').css("opacity", 1);

heres the FN extension..

这是 FN 扩展名..

(function($) {
$.fn.vAlign = function() {
    return this.each(function(i) {
        var h = $(this).height();
        var oh = $(this).outerHeight();
        var mt = (h + (oh - h)) / 2;
        $(this).css("margin-top", "-" + mt + "px");
        $(this).css("top", "50%");
        $(this).css("position", "absolute");
    });
};

})(jQuery);

})(jQuery);

采纳答案by Donald Harvey

You could try using a CSS technique to vertically centre items, as shown here. I believe the method is cross-browser, though unfortunately it adds an extra div to your markup.

你可以尝试使用一个CSS技术垂直中心项目,如图所示这里。我相信该方法是跨浏览器的,但不幸的是它为您的标记添加了一个额外的 div。

It'd be fairly easy to apply this css to the markup using jQuery, using $().css()

将此 css 应用到使用 jQuery 的标记相当容易,使用 $().css()