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

时间:2013-02-26 13:34:20

标签: jquery html center

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

这里是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;}

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

3 个答案:

答案 0 :(得分:10)

如果您使用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();
});

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

答案 1 :(得分:1)

它的工作原理......将其潜入#sample

将其css样式设为

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

认为它有效..

答案 2 :(得分:0)

尝试这个:

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

使用选择器更改#div。

相关问题