JQuery width()不返回正确的值

时间:2013-02-25 13:19:47

标签: jquery css

我的css中没有预设宽度的div,我试图使用JQuery在屏幕上居中,它适用于 Chrome Firefox IE8 + ,但无法在 IE7 中使用。为什么呢?

的CSS:

.productBoxWrapper{
    height:210px;
    clear:both;
    background-color:blue;
}

JQuery的:

$('#mydiv').css("position", "absolute");
this.css("left", ($(window).width() - $("#mydiv").width()) / 2 + "px");

JSFiddle: http://jsfiddle.net/tygcz/3/

1 个答案:

答案 0 :(得分:1)

尝试将其置于中心位置:

的CSS:

#myDiv{
     position: absolute; top: 50%; left: 50%;
}

脚本:

$('#myDiv').css('marginLeft', - ( parseInt( $('#myDiv').width() ) / 2) + 'px' );
$('#myDiv').css('marginTop', - ( parseInt( $('#myDiv').height() ) / 2) + 'px' );

我不确定天气parseInt是否真的需要。

相关问题