如何将 div 元素定位在 ACTUAL 屏幕的中心?(JQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15090439/
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 14:20:44  来源:igfitidea点击:

How to position a div element at the center of the ACTUAL screen? (JQuery)

jqueryhtmlcenter

提问by Said Bahad?r Kaya

i need to position a div element at the center of the screen. I found a simple code below, but i need center of the ACTUAL screen, not "total height /2" of the page!

我需要在屏幕中央放置一个 div 元素。我在下面找到了一个简单的代码,但我需要实际屏幕的中心,而不是页面的“总高度/2”!

here is Jquery code that centers an element but not the actual screen;

这是将元素居中但不是实际屏幕的 Jquery 代码;

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;}

as i said, i need to calculate the actual screen sizes (like 1366*768 or whatever users resized their browsers) and position the element at the center of the screen. so, if i scroll down the page, always the centered div should be at the center, again.

正如我所说,我需要计算实际屏幕尺寸(如 1366*768 或任何用户调整浏览器大小的尺寸)并将元素定位在屏幕中央。所以,如果我向下滚动页面,居中的 div 应该再次位于中心。

回答by Goran Mottram

If you're okay with using fixedpositioning instead of absolute, you can use something like the following:

如果您可以使用fixed定位而不是absolute,则可以使用以下内容:

jQuery.fn.center = function ()
{
    this.css("position","fixed");
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

$('#myDiv').center();
$(window).resize(function(){
   $('#myDiv').center();
});

Demo: http://jsfiddle.net/GoranMottram/D4BwA/1/

演示:http: //jsfiddle.net/GoranMottram/D4BwA/1/

回答by sasi

it works..take this dive it as #sample

它有效..把这次潜水当作 #sample

give its css style as

将其 css 样式设置为

#sample{
margin-left:auto;
margin-right:auto;
width:200px;//your wish
}

think it works..

认为它有效..

回答by harikrishnan.n0077

TRY THIS:

尝试这个:

var width=$("#div").css("width");
var half=width/2;
$("#div").css("marginLeft","-"+half+"px");

Change #div with your selector.

使用选择器更改 #div。